Reputation: 269
How would I go about turning this function into a generic type?
func addThreeValue(value1:String,value2:String,value3:String) -> String {
let concatenated = value1 + value2 + value3
return concatenated
}
Upvotes: 0
Views: 39
Reputation: 118731
This will not work:
func addThreeValues<T>(v1: T, _ v2: T, _ v3: T) -> T {
return v1 + v2 + v3
}
Because the compiler doesn't know about any +
operator which works with T
s.
You need to constrain the generic parameter so that it can find a suitable +
operator. The IntegerType protocol provides one:
func addThreeValues<T: IntegerType>(v1: T, _ v2: T, _ v3: T) -> T {
return v1 + v2 + v3
}
However, String doesn't conform to the IntegerType protocol:
addThreeValues("a", "b", "c") // error: cannot invoke 'addThreeValues' with an argument list of type '(String, String, String)'
To work around this you could define your own protocol and provide conformances for whichever types you want to use:
protocol Addable {
func +(lhs: Self, rhs: Self) -> Self
}
extension String: Addable {}
extension Int: Addable {}
func addThreeValues<T: Addable>(v1: T, _ v2: T, _ v3: T) -> T {
return v1 + v2 + v3
}
Now this works:
addThreeValues(1, 2, 3) // returns 6
addThreeValues("a", "b", "c") // returns "abc"
Upvotes: 1