1

我正在尝试为 Array 结构创建扩展,以便在包含的对象符合特定协议的情况下添加方法,但是当我尝试从类访问扩展中的方法时,我遇到了奇怪的行为。

这是我的游乐场代码

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

知道有什么问题吗?

4

1 回答 1

0

好的,看起来这是一个众所周知的行为......对于某人来说是一个错误。

实际上,不,这只是编译器的一个已知限制。不幸的是,今天,协议类型(或我们编译器中称之为“存在”的)不符合协议:

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'  

来源:https ://forums.developer.apple.com/message/15955#15955

于 2015-08-19T11:42:17.463 回答