Created
August 29, 2014 07:32
-
-
Save beccadax/f85ede7dd7b26c6e716e to your computer and use it in GitHub Desktop.
Adds a prefix ^ operator which allows widening conversions between numeric types.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let i8 = Int8(42) | |
let i16 = Int16(42) | |
let i32 = Int32(42) | |
let i64 = Int64(42) | |
^i8 + i16 | |
let f = Float(42.0) | |
let cgf = CGFloat(42.0) | |
let d = Double(42.0) | |
^f + d | |
^f + cgf | |
^cgf + d | |
d + ^i32 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
prefix operator ^ {} | |
// Int8 widens to Int16, Int32, and Int64 | |
prefix func ^ (x: Int8) -> Int16 { | |
return Int16(x) | |
} | |
prefix func ^ (x: Int8) -> Int32 { | |
return Int32(x) | |
} | |
prefix func ^ (x: Int8) -> Int64 { | |
return Int64(x) | |
} | |
// Int16 widens to Int32 and Int64 | |
prefix func ^ (x: Int16) -> Int32 { | |
return Int32(x) | |
} | |
prefix func ^ (x: Int16) -> Int64 { | |
return Int64(x) | |
} | |
// Int32 widens to Int64 | |
prefix func ^ (x: Int32) -> Int64 { | |
return Int64(x) | |
} | |
// Float widens to Double | |
prefix func ^ (x: Float) -> Double { | |
return Double(x) | |
} | |
// Float <= CGFloat <= Double, so you can widen a Float to CGFloat and a CGFloat to Double | |
prefix func ^ (x: Float) -> CGFloat { | |
return CGFloat(x) | |
} | |
prefix func ^ (x: CGFloat) -> Double { | |
return Double(x) | |
} | |
// Int8 and Int16 widen to Float and CGFloat. | |
prefix func ^ (x: Int8) -> Float { | |
return Float(x) | |
} | |
prefix func ^ (x: Int16) -> Float { | |
return Float(x) | |
} | |
prefix func ^ (x: Int8) -> CGFloat { | |
return CGFloat(x) | |
} | |
prefix func ^ (x: Int16) -> CGFloat { | |
return CGFloat(x) | |
} | |
// Int8, Int16, and Int32 widen to Double | |
prefix func ^ (x: Int8) -> Double { | |
return Double(x) | |
} | |
prefix func ^ (x: Int16) -> Double { | |
return Double(x) | |
} | |
prefix func ^ (x: Int32) -> Double { | |
return Double(x) | |
} | |
// Int64 and, by extension, Int can't safely widen to anything. (Well, I guess Float80, but nobody uses that.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment