簡體   English   中英

如何創建特定類型的對象數組,符合 Swift 2 中的協議

[英]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框架也使用NSObjectNSObjectProtocol做到這一點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM