我可以在Swift中为通用类型T分配默认类型吗? [英] Can I assign a default type to generic type T in Swift?
问题描述
我有一个通用类,希望能够与默认类型一起使用.现在,我可以使用任何类型对其进行初始化,但必须明确.
I have a generic class that I want to be able to use with a default type. Right now I can initialize it with any type, but I have to be explicit.
//Initialize with a type
MyManager<MyCustomerObject>()
// Initialize with NSObject (what I want to be my default type)
MyManager<NSObject>()
// This doesn't work, but I want this kind of functionality
class MyManager<T = NSObject> {}
// So I can create my manager like so and it inserts the default type as NSObject
MyManager() //Or MyManager<>()
在Swift中有可能吗?
Is this possible in Swift?
推荐答案
不支持默认的通用参数,但是您可以通过在类型受限的扩展上定义默认的init()
来伪造它,在这种情况下,编译器将足够聪明,可以使用这种类型.例如:
There's no support for default generic arguments, but you can fake it by defining the default init()
on a type-constrained extension, in which case the compiler will be smart enough to use that type. E.g.:
class MyManager<T> {
let instance: T
init(instance: T) {
self.instance = instance
}
}
extension MyManager where T == NSObject {
convenience init() {
self.init(instance: NSObject())
}
}
现在您可以不使用任何参数来初始化类型,它将默认为MyManager<NSObject>
:
And now you can initialize the type with no argument and it will default to MyManager<NSObject>
:
let mm1 = MyManager(instance: "Foo") // MyManager<String>
let mm2 = MyManager(instance: 1) // MyManager<Int>
let mm3 = MyManager() // MyManager<NSObject>
SwiftUI经常使用这种技术.
SwiftUI uses this technique quite a lot.
这篇关于我可以在Swift中为通用类型T分配默认类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!