0

我相信这对你来说是一个简单的问题。

如何用一个 GKState 编写一个带有两个参数的函数?

更新

苹果使用 func willExitWithNextState(_ nextState: GKState)

如果我使用somefunc(state:GKState) 效果很好

虽然somefunc(state:GKState, string:String) 不起作用,为什么???

其他示例

我试过这个:

class Pippo:GKState {}

//1
func printState (state: GKState?) {
    print(state)
}

printState(Pippo) //Error cannot convert value of type '(Pippo).Type' (aka 'Pippo.Type') to expected argument type 'GKState?'

//2
func printStateAny (state: AnyClass?) {
    print(state)
}
printStateAny(Pippo) //NO Error


//3
func printStateGeneral <T>(state: T?) {
    print(state)
}
printStateGeneral(Pippo) //No Error

//4
func printStateAnyAndString (state: AnyClass?, string:String) {
    print(state)
    print(string)
}

printStateAnyAndString(Pippo/*ExpectedName Or costructor*/, string: "Hello") //ERROR
printStateAnyAndString(Pippo()/*ExpectedName Or costructor*/, string: "Hello") //ERROR cannot convert value of type 'Pippo' to expected argument type 'AnyClass?'

解决方案感谢@0x141E

func printStateAnyAndString (state: GKState.Type, string:String) {
    switch state {
    case is Pippo.Type:
        print("pippo")
    default:
        print(string)
    }
}

printStateAnyAndString(Pippo.self, string: "Not Pippo")

谢谢您的回复

4

2 回答 2

0

如果您希望参数成为类,请使用Class.TypeAnyClass

func printState (state: AnyClass, string:String) {
    print(state)
    print(string)
}

Class.self用作论据

printState(Pippo.self, string:"hello pippo")

更新

如果您的函数定义是

func printState (state:GKState, string:String) {
    if state.isValidNextState(state.dynamicType) {
        print("\(state.dynamicType) is valid")
    }
    print(state)
    print(string)
}

您需要传入 的实例GKState(或 的子类GKState)作为第一个参数,而不是类/子类本身。例如,

let pippo = Pippo()

printState (pippo, "Hello")
于 2016-02-03T07:04:15.653 回答
0

在整个示例代码中,您使用了 AnyClass,而您应该(可能)使用 AnyObject。AnyClass 指的是类定义,而 AnyObject 是类的实例。

class MyClass { }

func myFunc1(class: AnyClass)
func myFunc2(object: AnyObject)

let myObject = MyClass() // create instance of class

myFunc1(MyClass)         // myFunc1 is called with a class
myFunc2(myObject)        // myFunc2 is called with an instance

您还使用“?”将大多数参数设为可选,而它看起来并不需要。例如:

printState(nil) // What should this do?
于 2016-02-01T22:56:47.673 回答