Search code examples
iosswift2swift-playground

How two UInt8 variables are added in iOS Swift?


Say there are two variables:

let number1 : UInt8 = 100;
let number2 : UInt8 = 100;

You add and print them

print(number1 + number2)  //This prints 200

Now define one more

let number3 : UInt8 = 200;

And try to add now

print(number1 + number3)  // Throws execution was interrupted

I understand that the sum of number1 and number3 would be out of range of UInt8 but explicit casting also does not help, for example following line also gives the same error:

print(UInt8(number1 + number3)) // Throws execution was interrupted

The way I found was to do the following:

print(Int(number1) + Int(number3))

Is there a better way of adding UInt8 number when their sum goes out of range?


Solution

  • As you've said casting both UInt8 variables to Int overrides the default exception on overflow as the resulting Int now has room to fit the sum.

    To avoid casting the variables for every operation we would like to overload the operator like this:

    func + (left: UInt8, right: UInt8) -> Int {
       return Int(left) + Int(right)
    }
    

    However this will give us a compiler error as the + operator is already defined for adding two UInt8's.

    What we could do instead is to define a custom operator, say ^+ to mean addition of two UInt8's but add them as Int's like so:

    infix operator ^+ { associativity left precedence 140 }
    
    func ^+ (left: UInt8, right: UInt8) -> Int {
        return Int(left) + Int(right)
    }
    

    Then we can use it in our algorithms:

    print(number1 ^+ number3) // Prints 300
    

    If you however want the result to just overflow you can use the overflow operators from the standard library:

    print(number1 &+ number3) // Prints 44