我想在协议(protocol)中指定一个函数,其返回值与当前实现类的类型相匹配。
protocol MakesSelf {
static func getInstance<T>() -> T
}
除非 T 被限制为与实现 MakesSelf 的人相同的类型,例如
class MyThing: MakesSelf {
class func getInstance<T>() -> T {
return MyThing()
}
}
我的理解是,编译器会根据返回值为 T 分配 MyThing 的类型,但我得到的是类型转换错误:无法转换 ' 类型的返回表达式MyThing' 返回类型 'T'
最佳答案
您可以创建一个具有关联类型的协议(protocol),您的 getInstance()
函数将返回该类型。在协议(protocol)的扩展中创建该功能的默认实现。完整示例:
protocol Initializable {
init()
}
protocol MakesSelf: Initializable {
associatedtype Object: Initializable = Self
static func getInstance() -> Object
}
extension MakesSelf {
static func getInstance() -> Object {
return Object()
}
}
class MyThing: MakesSelf {
required init() {}
func printSelf() {
print(MyThing.self)
print(Object.self)
// Both will print "MyThing" because Object is a typealias of MyThing class
}
}
然后获取您的实例:
let instance = MyThing.getInstance()
print("\(instance.self)")
/* Will print: MyTestApp.MyThing */
如您所见,因为您已经在协议(protocol)的扩展中给出了 getInstance()
的默认实现,这在符合类中不是必需的。在您的问题的上下文中,关联类型用作“占位符”。
关于ios - 我可以使用基于返回值的设置占位符类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50254617/