On the contrary, Swift language should be unaware of prefix minus or prefix plus or any other prefix operator. Plus on a custom type (which can be integer literal expressible among other things) can do arbitrary things instead of returning self
unchanged, and prefix minus should be parsed as a proper operator to avoid the anomalies mentioned above or similar, IMHO.
Looks a lesser evil to me.
How often do you have to write "-2146483648" (or 2146483647 FTM) †? Perhaps you can do the same and use .min / .max instead of -128 / 127
(† - yes, there's a typo and that's to stress the point.)
Edit: IIRC (yep, e.g. here, search for SCHAR_MIN), C used the notion of INT_MIN / INT_MAX not only to account for different size in bits, but to be compatible with weird one's complement architectures where INT8_MIN is -127
. Ok, ok, we'll probably never need to support that in Swift. Right?
Edit2: I used to ask this question (or rather its C equivalent) in the interviews
func isqrt(_ x: Int) -> Int {
precondition(x >= 0)
return Int(sqrt(Double(x)))
}
// 🐞 not so safe 🐞
func safeSqrt(_ x: Int) -> Int {
var x = x
if x < 0 { x = -x }
return isqrt(x)
}
Edit3: another funny + / - asymmetry:
enum SpecialNumbers: Double {
case negativeZero = -0.0
case zero = 0.0
case positiveZero = +0.0 // 🛑 Enum case must declare a raw value when the preceding raw value is not an integer
}