如何在Swift中进行通用扩展?
我想做一个通用的扩展,以避免我为不同的类型重复我的代码。这是我需要修复的代码!
extension Bool {
func print() { Swift.print(self.description) }
}
extension Int {
func print() { Swift.print(self.description) }
}
extension String {
func print() { Swift.print(self.description) }
}
extension <T> {
func print() { Swift.print(self.description) }
}
回答
您的扩展不是“通用的”,因为它可以适用于任何类型。它只能应用于具有description属性的类型。那么,哪些类型有description属性?每种符合的类型CustomStringConvertible都可以!
所以你应该创建一个扩展CustomStringConvertible:
extension CustomStringConvertible {
func print() { Swift.print(self.description) }
}
(请注意,可能存在具有description属性但不符合 的CustomStringConvertible类型,但标准库中的大多数类型都不是这样的)
真正通用的扩展是别的东西,目前正在被提议,即还不是 Swift 的一部分。
- @mimi You should make your custom type conform to `CustomStringConvertible`. e.g. `class CustomType: CustomStringConvertible { var description: String { ... } }`