I want to write a generic function that will return a sum of it's two parameters, like the one below:
func add<T: ???>(left: T, right: T) -> T {
return left+right
}
Of course, in order to use +
operator, T
type needs to conform to a protocol that defines +
operator.
In case of several other operators, there are built in protocols - e.g. Equatable
for ==
, and Comparable
for <
, >
etc. Those protocols are adopted by all Swift's built in "arithmetic" types like Double, Float, Int16 etc.
Is there a standard protocol that defines +
,-
,*
,/
operators, which is adopted by ALL "arithmetic" types like Double, Float, Int, UInt, Int16 etc.?
There isn't anything in the library for that, I get what you mean. You can do it yourself though:
protocol Arithmetic {
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
}
extension Int8 : Arithmetic {}
extension Int16 : Arithmetic {}
extension Int32 : Arithmetic {}
extension Int64 : Arithmetic {}
extension UInt8 : Arithmetic {}
extension UInt16 : Arithmetic {}
extension UInt32 : Arithmetic {}
extension UInt64 : Arithmetic {}
extension Float80 : Arithmetic {}
extension Float : Arithmetic {}
extension Double : Arithmetic {}
func add<T: Arithmetic>(a: T, b: T) -> T {
return a + b
}
add(3, b: 4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With