The Upconvert framework allows convenient, lossless conversions between different types in Swift 4. Conversion is performed using the upconversion operator, ^:
let small: Int8 = 1
let large: Int = 100_000
print(large + ^small) // => 100002Upconversion is only allowed when the destination type is large enough to contain all possible values of the source type. Otherwise, your code will not compile.
let small: Int8 = 1
let large: Int = 100_000
large + ^small // OK
^large + small // ErrorUpconvert ships with the following conversions built in:
Int8→Int16→Int32→Int→Int64UInt8→UInt16→UInt32→UInt→UInt64Float→CGFloat→Double→Float80Substring→StringUnicodeScalar→Character→StringKeyPath→ getter function
The KeyPath upconversion allows you to use key paths with functions like map and filter:
let names = people.map(^\.name)You can add your own upconversions by conforming types to the Upconvertible protocol.
Just clone it and put the project into Xcode. Pull requests to support package managers are welcome.
-
Downconversions—potentially lossy conversions—are not supported.
-
Each type can only upconvert to one other type (plus the type it upconverts to, recursively). This is why you can't upconvert a
UInt32to anInt64. -
The
^operator will only recurse so far (five levels currently). -
The
IntandUIntconversion sequences don't support the newDoubleWidthtype due to limitations in its current implementation. -
This design is bleeding-edge; don't consider the interface to be stable yet.
Brent Royal-Gordon, Architechies.
Copyright © 2017 Architechies. Distributed under the MIT License.