swift – 如何使用函数作为值声明字典并使用整数键入?
发布时间:2020-12-14 04:42:38 所属栏目:百科 来源:网络整理
导读: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
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
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
