1

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??

Giuseppe Lanza
  • 3,519
  • 1
  • 18
  • 40
  • 1
    I have to say it looks like a bug. I even tried renaming the function to `myIndexOf` in case it was getting confused by the type inference, but no dice. – JeremyP Aug 18 '15 at 16:35

1 Answers1

0

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

Giuseppe Lanza
  • 3,519
  • 1
  • 18
  • 40