如何使用函数作为值声明字典并使用整数键入?

zs2*_*020 5 dictionary function swift swift2

struct Test {
    func isOk () -> Bool{
        return true
    }

    var mapping: [Int: () -> Bool] = [
        1: isOk
    ]

    func test() -> Bool {
        return mapping[1]()
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

Cannot convert value of type '(Test) -> () -> Bool' to expected dictionary value type '() -> Bool'
Run Code Online (Sandbox Code Playgroud)

任何的想法?谢谢!

Ale*_*ica 5

你看到这个奇怪的类型((Test) -> () -> Bool),因为Swift实例方法是curried函数.

如果isOk可以接受静态方法,则可以这样做:

struct Test {
    static func isOk() -> Bool { //Make it static
        return true
    }

    var mapping: [Int : () -> Bool] = [
        1 : Test.isOk // Static method must be qualified by its parent type
    ]

    func test() -> Bool { //Bool return value necessary
        //TODO: remove force unwrapping.
        return mapping[1]!() //subscripting a Dict might return nil
    }
}
Run Code Online (Sandbox Code Playgroud)

如果isOk必须保留为实例方法,则可以执行以下操作:

struct Test {
    func isOk() -> Bool {
        return true
    }

    var mapping: [Int : (Test) -> () -> Bool] = [ //change type
        1 : isOk
    ]

    //the instance method received from the dict needs an instance to act on
    func test(instance: Test) -> Bool { //Bool return value necessary
        //TODO: remove force unwrapping.
        return mapping[1]!(instance)() //curried function call
    }
}
Run Code Online (Sandbox Code Playgroud)