[英]How can I make a generic extension in Swift?
I want make a generic extension for avoiding me to repeating my code for deferent types.我想做一个通用扩展,以避免我重复我的不同类型的代码。 here is my code need to get fixed!
这是我的代码需要修复!
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) }
}
Your extension is not "generic" in the sense that it can apply to any type.从可以应用于任何类型的意义上说,您的扩展不是“通用的”。 It can only apply to types that have a
description
property.它只能应用于具有
description
属性的类型。 Well, which types have a description
property?那么,哪些类型具有
description
属性? Every type that conforms to CustomStringConvertible
does!符合
CustomStringConvertible
的每种类型都可以!
So you should create an extension of CustomStringConvertible
:所以你应该创建一个
CustomStringConvertible
的扩展:
extension CustomStringConvertible {
func print() { Swift.print(self.description) }
}
(Note that there could be a type that have a description
property, but does not conform to CustomStringConvertible
, but most types in the standard libraries aren't like this) (请注意,可能有一个类型具有
description
属性,但不符合CustomStringConvertible
,但标准库中的大多数类型都不是这样的)
Truly generic extensions are something else , and is currently being proposed, ie not part of Swift yet.真正通用的扩展是另外一回事,目前正在提议中,即尚未成为 Swift 的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.