jiangjiefs jiangjiefs - 1 month ago 8
Swift Question

In Swift, How to extend a protocol with generic type?

I want to add a function to all the classes that implement Comparable , such as Int, Float, CGFloat. Here is my code with error reported:

extension Comparable{
func constraintBetween<T: Comparable>(a:T , b: T) -> T{
if self < a {
return a
}else if self > b{
return b
}else{
return self
}
}
}


enter image description here
Anyone can help to make it right? Thanks in advance!

Answer

Self is the stand-in for the type adopting the protocol:

extension Comparable {
    func constraintBetween(a: Self, b: Self) -> Self {
        if self < a {
            return a
        } else if self > b {
            return b
        } else {
            return self
        }
    }
}
Comments