2015-08-18 63 views
1

我試圖創建一個擴展數組結構爲了添加方法,如果包含的對象符合特定的協議,但我有奇怪的行爲時我嘗試從類中訪問擴展中的方法。擴展數組元素符合協議在swift 2.0

這裏是我的遊樂場

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 

什麼是錯的任何想法碼?

+1

我不得不說,它看起來像一個錯誤。我甚至嘗試將函數重命名爲'myIndexOf',以防被類型推斷弄糊塗,但沒有骰子。 – JeremyP

回答

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