How to check if integer multiplication will overflow in Swift

1 Answer

0 votes
import Foundation

func multiplyWillOverflow(x: Int64, y: Int64) -> Bool {
    if x == 0 { return false }
    if y > Int64.max / x { return true }
    if y < Int64.min / x { return true }
    return false
}

var x: Int64 = 34
var y: Int64 = 14727836
print(multiplyWillOverflow(x: x, y: y) ? "true" : "false")

x = 133883
y = 985698018999383
print(multiplyWillOverflow(x: x, y: y) ? "true" : "false")



/*
run:

false
true

*/

 



answered May 18, 2025 by avibootz
...