有人可以解释这个错误以及为什么这对闭包有效吗?
如果您在“B”类中将“测试”更改为“A”,则两种情况下一切正常。
测试版 7
protocol Test {
func someFunc() -> String
var someClosure: () -> Int { get }
}
class A: Test {
func someFunc() -> String {
return "A String"
}
var someClosure: () -> Int {
return {
return 2
}
}
}
class B {
let a: Test
let aString: () -> String
let aInt: () -> Int
init(a: Test){
self.a = a
aString = a.someFunc // Error: Partial application of protocol method is not allowed
aInt = a.someClosure // Works fine
}
}
更新
还有我的奇葩段错集https://gist.github.com/aleksgapp/795a2d428008bdfa4823
如果您有任何想法,请不要犹豫发表评论。
最佳答案
更新(感谢 Laszlo Korte)
From Xcode 7 Beta 2 with Swift 2.0 Release Notes: Non-mutating methods of structs, enums, and protocols may now be partially applied to their “self” parameter.
例如:
let a: Set<Int> = [1, 2]
let b: [Set<Int>] = [[1], [3]]
b.map(a.union) // [[1, 2], [1, 2, 3]]
原始答案(适用于带有 Swift 1.2 的 Xcode 6)
协议(protocol)可以被类、结构或枚举采用。在最后两种情况下,结构或枚举方法的部分应用是不允许的,你会得到“协议(protocol)方法的部分应用是不允许的”,因为 a: Test
可以是结构或枚举。
部分应用的方法或函数换句话说就是柯里化(Currying)的方法或函数
。因此,当您编写 a.someFunc
时,您会尝试部分应用此方法,即获取对隐式持有对 a
的引用的闭包的引用。但是结构和枚举不是引用类型,它们是值类型并且没有对a
的引用。
关于methods - 不允许部分应用协议(protocol)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25684766/