jiangjiefs
jiangjiefs

Reputation: 149

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!

Upvotes: 1

Views: 1157

Answers (1)

russbishop
russbishop

Reputation: 17229

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

Upvotes: 4

Related Questions