使用符合 swift 2.0 协议的元素扩展数组
Extension of array with Elements conforming a protocol in swift 2.0
我正在尝试为 Array 结构创建一个扩展,以便在包含的对象符合特定协议时添加方法,但是当我尝试访问来自 class.
的扩展
这是我的游乐场代码
protocol SomeInt {
var theInt: Int {get set}
}
extension Array where Element: SomeInt {
func indexOf(object:SomeInt) -> Index? {
return indexOf({ (obj) -> Bool in
return obj.theInt == object.theInt
})
}
}
class PRR: SomeInt {
var theInt: Int = 0
init(withInt value: Int){
theInt = value
}
}
class container {
var items: [SomeInt]!
}
let obj1 = PRR(withInt: 1)
let obj2 = PRR(withInt: 2)
let arr = [obj1, obj2]
arr.indexOf(obj1) //this succeds
let cont = container()
cont.items = [obj1, obj2]
cont.items.indexOf(obj1) //this doesn't
知道哪里出了问题吗??
好的,看起来这是一个众所周知的行为...因为有人是一个错误。
Actually, no, this is just a known limitation of the compiler. Unfortunately, today, the protocol type (or "existential" as we compiler weenies call it) doesn't conform to the protocol:
protocol P {}
func g<T: P>(_: T) {}
struct X : P {}
struct Y<T: P> {}
Y<P>() // error: type 'P' does not conform to protocol 'P'
我正在尝试为 Array 结构创建一个扩展,以便在包含的对象符合特定协议时添加方法,但是当我尝试访问来自 class.
的扩展这是我的游乐场代码
protocol SomeInt {
var theInt: Int {get set}
}
extension Array where Element: SomeInt {
func indexOf(object:SomeInt) -> Index? {
return indexOf({ (obj) -> Bool in
return obj.theInt == object.theInt
})
}
}
class PRR: SomeInt {
var theInt: Int = 0
init(withInt value: Int){
theInt = value
}
}
class container {
var items: [SomeInt]!
}
let obj1 = PRR(withInt: 1)
let obj2 = PRR(withInt: 2)
let arr = [obj1, obj2]
arr.indexOf(obj1) //this succeds
let cont = container()
cont.items = [obj1, obj2]
cont.items.indexOf(obj1) //this doesn't
知道哪里出了问题吗??
好的,看起来这是一个众所周知的行为...因为有人是一个错误。
Actually, no, this is just a known limitation of the compiler. Unfortunately, today, the protocol type (or "existential" as we compiler weenies call it) doesn't conform to the protocol:
protocol P {}
func g<T: P>(_: T) {}
struct X : P {}
struct Y<T: P> {}
Y<P>() // error: type 'P' does not conform to protocol 'P'