Reputation: 13760
I have the following function:
func myFunc<T>(t1: T, t2: T) -> T {
return t1 + t2
}
The compiler (rightfully) does not allow this because it does not know whether T
supports addition. Is there a way to specify that T
must support addition, in the same way that one can specify that T
must conform to a given protocol? I looked online and couldn't find anything about a protocol that guarantees support for +
.
Upvotes: 0
Views: 150
Reputation: 25459
You need to specify that the type (T) support addition. You can do it by declaring custom protocol, for example:
protocol Addition {
func +(lhs: Self, rhs: Self) -> Self
}
Now just specify that T implement it:
func myFunc<T: Addition>(t1: T, t2: T) -> T {
return t1 + t2
}
The last step is extend the type you want to pass as a parameter to your function to implement this protocol, for example Int:
extension Int: Addition {}
You don't even have to implement + function because Int already does it. You could extend any type you want including others protocols to implement Addition one and after that safety pass it to your function:
myFunc(2, t2: 4)
// EDITED
You could use protocol IntegerArithmeticType
which implement +, -, *, /, % but it all depends on your requirements.
If you create custom class which you want to pass instance to your function you have to implement all of the operation but if you going to only call your function on standard types like Int. You save time and you don't need to create custom protocol. Example:
func myFunc<T: IntegerArithmeticType>(t1: T, t2: T) -> T {
return t1 + t2
}
myFunc(2, t2: 4)
Upvotes: 1