Search code examples
genericsswift2swift-extensions

Extension of array with Elements conforming a protocol in swift 2.0


i'm trying to create an extension for the Array struct in order to add methods just if the contained objects conforms to a particular protocol, but i'm having strange behaviors when i try to access to a method in the extension from a class.

here is my code for a playground

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

Any idea on what's wrong??


Solution

  • Ok, looks like it is a well known behavior... for someone is a bug.

    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'  
    

    source: https://forums.developer.apple.com/message/15955#15955