2015-06-13 70 views
1

(第一篇)斯威夫特:過濾協議陣列通過比較類型

通常即時通訊能夠在這裏或其他地方尋找答案,但沒有運氣這次=(

問:在斯威夫特,你怎麼過濾數組這是一個協議類型由作爲函數參數提供的實施類型?

protocol Aprotocol { 
    var number:Int { get set } 
} 

class Aclass: Aprotocol { 
    var number = 1 
} 

class AnotherClass: Aprotocol { 
    var number = 1 
} 

var array:[Aprotocol] = [ Aclass(), AnotherClass(), Aclass() ] 

func foo (parameter:Aprotocol) -> Int { 
    return array.filter({ /* p in p.self == parameter.self */ }).count 
} 

var bar:Aprotocol = // Aclass() or AnotherClass() 

var result:Int = foo(bar) // should return 2 or 1, depending on bar type 

也許這是所有

由於不正確的方法?!

回答

0

這是我想你想:

return array.filter { (element: Aprotocol) -> Bool in 
    element.dynamicType == parameter.dynamicType 
}.count 

但是我推薦這個,這不相同,但沒有被傳入的Aclass()無用實例頂部的答案。另外這種方式速度更快:

func foo <T: Aprotocol>(type: T.Type) -> Int { 
    return array.filter { (element: Aprotocol) -> Bool in 
     element.dynamicType == type 
    }.count 
} 

var result:Int = foo(Aclass) 

dynamicType將返回一個實例

+0

很好,我可以看到爲什麼這樣的作品,謝謝! –

0

非常簡單:

return array.filter({ parameter.number == $0.number }).count 
+0

假裝了一會兒,該財產的價值忍不住了,你有比較類型做了評價(編輯示例更清晰) –

+0

@MattiasLundblad我貼了另外一個我認爲這是你想要的;) – Kametrixom

0

Kametrixoms解決方案有效的類型(如果你用「是T」,而不是「==型」),但在我的情況下,因爲我不知道它的實現類是要調用它,只好用此解決方案:

protocol Aprotocol: AnyObject { 
    var number:Int { get set } 
} 

class func foo(parameter: AnyObject) -> Int {  
    return array.filter ({ (element: Aprotocol) -> Bool in 
    object_getClassName(element) == object_getClassName(parameter) 
    }).count 
}