Swift - is there a standard protocol that defines +, -, *, / functions, which is accepted by all types of "arithmetic", such as Double, Float, Int, etc.?

I want to write a generalized function that returns the sum of two parameters, such as:

func add<T: ???>(left: T, right: T) -> T {
    return left+right
}

Of course, to use an operator, the +type Tmust conform to the protocol defining the operator +.

In the case of several other operators, there are built-in protocols - for example, Equatablefor ==and Comparablefor <, >etc. These protocols are accepted by all Swift built into arithmetic types such as Double, Float, Int16, etc.

Is there a standard protocol that defines the operators +, -, *, /which are accepted by all "arithmetic" types such as Double, Float, Int, UInt, Int16 , etc.?

+4
source share
1 answer

There is nothing in the library for this, I understand 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)
+4
source

All Articles