Reputation: 149
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
}
}
}
Anyone can help to make it right? Thanks in advance!
Upvotes: 1
Views: 1157
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