![](/img/trans.png)
[英]iOS Swift: Array of Objects conforming to a Protocol: How to check if array contains
[英]How to create an array of objects of a specific type, conforming to a protocol in Swift 2
我的問題很簡單,希望只是語法問題。 我正在嘗試創建一個符合我的協議的 UIViewControllers 數組。 我能夠將此要求創建為函數參數:
func doSomething<T: UIViewController where T: MyProtocol>(controller: T) { ... }
現在,我想將這些對象存儲在一個數組中,我希望我可以有這樣的東西:
var viewControllers = Array<T: UIViewController where T: MyProtocol>()
但是,我無法弄清楚如何在數組上創建此約束。 這是可能的還是我以錯誤的方式處理它?
您最好的選擇可能是使用只有您的類符合的協議,並使用此協議來約束您的類型:
protocol ClassProtocol {}
class Class : ClassProtocol {}
protocol Protocol {}
class SubClass : Class, Protocol {}
let x : protocol<ClassProtocol, Protocol> = SubClass()
Foundation
框架也使用NSObject
和NSObjectProtocol
做到這一點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.