Generics swift 2.0中具有符合协议元素的数组扩展
我试图为数组结构创建一个扩展,以便在所包含的对象符合特定协议的情况下添加方法,但当我试图从类访问扩展中的方法时,会出现奇怪的行为 这是我的游乐场代码Generics swift 2.0中具有符合协议元素的数组扩展,generics,swift2,swift-extensions,Generics,Swift2,Swift Extensions,我试图为数组结构创建一个扩展,以便在所包含的对象符合特定协议的情况下添加方法,但当我试图从类访问扩展中的方法时,会出现奇怪的行为 这是我的游乐场代码 protocol SomeInt { var theInt: Int {get set} } extension Array where Element: SomeInt { func indexOf(object:SomeInt) -> Index? { return indexOf({ (obj) -&g
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
有什么问题吗???好的,看起来这是一个众所周知的行为。。。对某人来说是一只虫子 事实上,这只是编译器的一个已知限制。不幸的是,今天,协议类型(或我们编译器weenies称之为“存在”)不符合协议:
协议P{}
func g(u:T){}
结构X:P{}
结构Y{}
Y()//错误:类型“P”不符合协议“P”
来源:好的,看起来这是一种众所周知的行为。。。对某人来说是一只虫子 事实上,这只是编译器的一个已知限制。不幸的是,今天,协议类型(或我们编译器weenies称之为“存在”)不符合协议:
协议P{}
func g(u:T){}
结构X:P{}
结构Y{}
Y()//错误:类型“P”不符合协议“P”
来源:我不得不说它看起来像一个bug。我甚至尝试将函数重命名为
myIndexOf
,以防它被类型推断弄糊涂,但这是毫无意义的。我不得不说,它看起来像一个bug。我甚至尝试将函数重命名为myIndexOf
,以防它被类型推断弄糊涂,但没有成功。
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'