swift - 如何声明以函数为值并以整数为键的字典?

标签 swift function dictionary swift2

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

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

    func test() -> Bool {
        return mapping[1]()
    }
}

我遇到了这个错误:

Cannot convert value of type '(Test) -> () -> Bool' to expected dictionary value type '() -> Bool'

有什么想法吗?谢谢!

最佳答案

你看到这个奇怪的类型 ((Test) -> () -> Bool) 因为 Swift instance methods are curried functions .

如果将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
    }
}

如果 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
    }
}

关于swift - 如何声明以函数为值并以整数为键的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38130377/

相关文章:

ios - LayerKit 的 newConversationWithParticipants 总是在第一次调用时抛出 FMDatabase "not an error"

Swift 3 - 线程 1 : Signal SIGABRT Unrecognised selector sent to Instance

javascript jquery 函数这有点错误吗?

r - 如何使用lapply定义多个变量?

python - 如何将列表中的每个字典转换为Python中的嵌套字典?

java - 摆脱 Map 中的泛型

python - 摩尔斯电码到英语 python3

Swiftlint 自动更正不修改文件

带有 where 子句的 Swift 数组扩展不适用于子协议(protocol)

c++ - 传递给共享库的模板函数 (c++)