let value: Int16 = -32768
let a = Int64(abs(value))
you can paste these simple code inside playground and run it, it will cause a crash, what's wrong?
let value: Int16 = -32768
let a = Int64(abs(value))
you can paste these simple code inside playground and run it, it will cause a crash, what's wrong?
The highest number you can fit in Int16 is 32767, so 32768 doesn't fit. You are trying to convert your number to Int64, but you're doing it too late - it already crashed. You should convert first, then call abs.
let a = abs(Int64(value))
thanks for reply!
It's so easy to make a mistake~
if the value range for Int16 is from -32767 to 32768, it will be a lot safer for this case. just kidding~
There are two ways to get the absolute value of a signed integer x
, which each have some advantages and disadvantages:
The free function abs(x: T) -> T
returns a value with the same return type as its argument, which is often useful in arithmetic expressions. On the downside, for the minimum value of each signed integer type, the result is not representable, so it traps.
x.magnitude
returns an unsigned integer of type T.Magnitude
, which is guaranteed to be able to represent every possible value, so never traps, but is sometimes less convenient in actual use because it has a different type.
For a use case like yours, it's OK to get a different type back, so you can simply use value.magnitude
to avoid this problem.
let value: Int16 = -32768
let a = Int64(value.magnitude)
Yes, this is a better solution