[英]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.