[英]How can I make a generic extension in 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 的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.