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

swift – 如何使用函数作为值声明字典并使用整数键入?,第1张

概述struct Test { func isOk () -> Bool{ return true } var mapping: [Int: () -> Bool] = [ 1: isOk ] func test() -> Bool { return mapping[1]() }} 我收到了这个错误:
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'

任何的想法?谢谢!

解决方法 你看到这种奇怪的类型((测试) – >() – > 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 – 如何使用函数作为值声明字典并使用整数键入?全部内容,希望文章能够帮你解决swift – 如何使用函数作为值声明字典并使用整数键入?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1007238.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存