的一種方法如下:
protocol Protocol {
func bar()
}
class MyViewController : UIViewController, Protocol {
func bar() {
print("Bar")
}
static func getInstance() -> MyViewController {
return self.init()
}
}
/* Example usage */
let foo = MyViewController.getInstance()
print(foo.dynamicType) // MyViewController
foo.bar() // Bar
/* Naturally works to pass foo to 'Protocol' type constrained function */
func foobar<T: Protocol>(fizz: T) {
fizz.bar()
}
foobar(foo) // bar
或者,對於更通用/可重複使用的方法(用於類/結構具有可用簡單的init()
初始化工廠方法):
/* Setup generic factory */
protocol FactoryInitializers {
init()
}
protocol FactoryMethods {
typealias T: FactoryInitializers
}
extension FactoryMethods {
static func getInstance() -> T {
return T()
}
}
protocol Factory : FactoryMethods, FactoryInitializers { }
/* Apply for your example, with conformance to 'Factory' (to get access
to default implementation 'getInstance' method) as well as a custom
protocol 'Protocol' */
protocol Protocol {
func bar()
}
class MyViewController : UIViewController, Factory, Protocol {
typealias T = MyViewController
func bar() {
print("Bar")
}
}
與上述較簡單版本的結果相同:
let foo = MyViewController.getInstance() // OK, MyViewController conforms to Factory
print(foo.dynamicType) // MyViewController
foo.bar() // Bar
/* Naturally works to pass foo to 'Protocol' type constrained function */
func foobar<T: Protocol>(fizz: T) {
fizz.bar()
}
foobar(foo) // bar