Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...