How to check if integer addition will overflow in Swift

1 Answer

0 votes
import Foundation

func addingWillOverflow(x: Int, y: Int) -> Bool {
    return (x > 0 && y > Int.max - x) || (x < 0 && y < Int.min - x)
}

var x = 39839299, y = 1472783642
print(addingWillOverflow(x: x, y: y) ? "true" : "false")

x = 9223372036854775807 // Int.max
y = 1
print(addingWillOverflow(x: x, y: y) ? "true" : "false")

 
 
/*
run:
 
false
true
 
*/

 



answered May 17, 2025 by avibootz

Related questions

...