我想实现仅支持类支持的协议的方法。为此,我已经定义了一个协议:Swift:限制类只支持协议
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
值得看http://stackoverflow.com/a/24051850/2710486 – zcui93