Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/118.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何创建符合Swift 2中协议的特定类型的对象数组_Ios_Swift_Swift2 - Fatal编程技术网

Ios 如何创建符合Swift 2中协议的特定类型的对象数组

Ios 如何创建符合Swift 2中协议的特定类型的对象数组,ios,swift,swift2,Ios,Swift,Swift2,我的问题很简单,希望只是语法问题。我正在尝试创建符合我的协议的UIViewController数组。我能够创建此需求作为功能参数: func doSomething<T: UIViewController where T: MyProtocol>(controller: T) { ... } func doSomething(控制器:T){…} 现在,我想将这些对象存储在一个数组中,我希望可以有如下内容: var viewControllers = Array<T: UIV

我的问题很简单,希望只是语法问题。我正在尝试创建符合我的协议的UIViewController数组。我能够创建此需求作为功能参数:

func doSomething<T: UIViewController where T: MyProtocol>(controller: T) { ... }
func doSomething(控制器:T){…}
现在,我想将这些对象存储在一个数组中,我希望可以有如下内容:

var viewControllers = Array<T: UIViewController where T: MyProtocol>()
var viewControllers=Array()

但是,我不知道如何在数组上创建此约束。这是可能的还是我走错了方向?

您最好的选择可能是使用只有您的类符合的协议,并使用此协议来约束您的类型:

protocol ClassProtocol {}
class Class : ClassProtocol {}

protocol Protocol {}

class SubClass : Class, Protocol {}


let x : protocol<ClassProtocol, Protocol> = SubClass()
协议类协议{}
类:类协议{}
协议{}
类子类:类,协议{}
设x:protocol=SubClass()

Foundation
框架也通过
NSObject
NSObjectProtocol

实现了这一点。虽然这可以限制数组中对象的类型,但每当我需要引用特定于UIViewController的属性时,我仍然需要向下转换数组中的对象(因为不知道它们都是UIViewController的子类)。对吗?@KyleZaragoza您可以在ClassProtocol中声明所需的属性。NSObject和NSObjectProtocol也是这样做的