Swift   发布时间:2022-04-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift – 如何使用函数作为值声明字典并使用整数键入?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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 – 如何使用函数作为值声明字典并使用整数键入?所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。