Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

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) }
    
}



 
question from:https://stackoverflow.com/questions/65546821/how-can-i-make-a-generic-extension-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. Well, which types have a description property? Every type that conforms to CustomStringConvertible does!

So you should create an extension of 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)

Truly generic extensions are something else, and is currently being proposed, i.e. not part of Swift yet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...