Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - is there a standard protocol that defines +,-,*,/ functions, which is adopted by all "arithmetic" types like Double, Float, Int etc.? [duplicate]

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.?

like image 326
Grzegorz D. Avatar asked Jul 09 '15 18:07

Grzegorz D.


1 Answers

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)
like image 108
Kametrixom Avatar answered Dec 31 '22 16:12

Kametrixom