【发布时间】:2016-04-07 15:28:56
【问题描述】:
我想实现只采用类支持协议的方法。为此,我定义了一个协议:
protocol TestProt {
func testMe() -> String
}
让我们做一个类声明:
class TestClass: TestProt {
func testMe() -> String {
return "test"
}
}
但是,我如何才能实现注册类,仅支持 TestProt 的类?
class FabricaClass {
// it is func take any classes :(
func registerMe(context: MyContext, class: AnyClass) -> String {
}
// i want something like this =)
// to the method took only classes supported protocols
// but it don't work for swift...
func registerMe(context: MyContext, class: AnyClass <TestProt>) -> String {
}
}
UPD:回答
protocol TestProt {
static func testMe() -> String
}
class TestClass: TestProt {
class func testMe() -> String {
return "test"
}
}
class MyContext {
}
class FactoryClass {
init<T: TestProt>(context: MyContext, regClass: T.Type) {
regClass.testMe()
}
}
let context = MyContext()
let factory = FactoryClass(context: context, regClass: TestClass.self)
感谢@dfri
【问题讨论】:
标签: swift