2016-03-02 19 views
0

我有一個名爲IdeaListener的協議和一個擴展了這個協議的元素數組。從Array中移除對象並通過協議實例

private var ideaListeners: [IdeaListener] 

我想,以便從給定的IdeaProtocol實例的數組中刪除一個對象創建擴展。

var myInstanceOfIdeaListener: IdeaListener 
... 
ideaListeners.removeObject(myInstanceOfIdeaListener) 

我已經在網上找到了很多解決方案,但沒有人能夠接受的協議作爲removeObject函數的參數。 爲了做到這一點,我寫了這個擴展:

extension Array { 

    mutating func removeObject(object: AnyObject) -> Element? { 

    for (index, objectToCompare) in self.enumerate() { 
     if let to = objectToCompare as? AnyObject where to == object { 
      return removeAtIndex(index) 
     } 
    } 
    return nil 
    } 
} 

但是,編譯說

二元運算符「==」不能適用於兩個「AnyObject」操作數。

爲什麼我不能使用==比較兩個AnyObject?你將如何檢查數組是否包含object

此外,我想改善此功能,在開始時添加一個類型檢查,以檢查object的類型是否實際上是數組中元素的類型。我不知道如何編碼這個概念。就像這樣:

guard object is /*type of elements in array*/ else { 
    return nil 
} 

我怎樣才能得到數組中的元素的類型?

+1

爲了使用'==',您需要'Equatable'一致性。 AnyObject沒有。因爲你的原因,最好用'==='運算符來檢查兩個對象引用是否實際相同。 – courteouselk

回答

0

你可以嘗試這樣的事情,而不是

let a = ObjectOfProtocol() 
    let b = ObjectNotOfProtocol() 
    let c = [a,b] 

    let d = c.filter { (x:AnyObject) -> Bool in 

     return !x.conformsToProtocol(Protocol); 
    } 

    print("filtered array: \(d)") //should only show [ObjectNotOfProtocol] 

這將刪除符合Protocol陣列中

所以不是做一個擴展的所有對象,可以只使用此過濾器

甚至可以將它添加爲method extension to the Protocol itself,所以你可以去像Protocol.filterFromArray(array)這樣的東西,它會返回的數組中的協議的所有對象過濾掉,如果你想它只是一個我thod呼叫並且沒有每次都寫出過濾器

+0

編輯:哎呀丟了!在回報聲明中 – Fonix