Lets say I have created this protocol and a couple of classes
import UIKit
protocol ControllerConstructorProtocol {
class func construct() -> UIViewController?
}
class MyConstructor: ControllerConstructorProtocol {
class func construct() -> UIViewController? {
return UIViewController()
}
}
class MyOtherConstructor: ControllerConstructorProtocol {
class func construct() -> UIViewController? {
return UITableViewController(style: .Grouped)
}
}
Now I want to declare an array that contains classes of objects that will conform to such protocol.
How can I declare it? Ideally I would like the compiler to check the array is correctly filled (at compile time) rather than checking it myself at (run time) with the as
operator.
This is what I have tried without success :(
This leads to a compile error:
'Any Object does not have a member named 'construct'
var array = [ MyConstructor.self, MyOtherConstructor.self, ] var controller = array[0].construct() // << ERROR here
Writing this is even worse, since the class itself does not conform to the protocol (their instances do)
Type 'MyConstructor.Type' does not conform to protocol 'ControllerConstructorProtocol'
var array: Array<ControllerConstructorProtocol> = [ MyConstructor.self, // << ERROR here MyOtherConstructor.self, ]
EDIT 2016/04/23: In Swift 2.2 (Xcode 7.3) it is possible to write @rintaro's original idea :)
let array: Array<ControllerConstructorProtocol.Type> = [
MyConstructor.self,
MyOtherConstructor.self,
]
let viewController = array[0].construct()
See Question&Answers more detail:os