I have the following code in a playground (Xcode 9.0.1):
import MapKit
enum Test: UInt {
case first
case second
case third
}
let test = Test(rawValue: 4) as Any
print(test) // nil
let type = MKMapType(rawValue: 999)
print(type == nil) // false
print(type!.rawValue) // 999
MKMapType is defined as
enum MKMapType : UInt
As the maximum value of a MKMapType is 5, I expect the initializer of the enum to fail and return nil. Instead it returns 999. Am I missing some ObjC/Swift bridging here or could this be a bug?
It is possible to initialize an enum's case through it's rawValue by using the enum's built-in initializers. Enums can also be used in recursions.
Enumerations in Swift are much more flexible, and don't have to provide a value for each case of the enumeration. If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.
A type that can be converted to and from an associated raw value.
enum s do have stored type properties - i.e., static properties. They don't have stored instance properties.
I filed a bug with Apple and this is the reply I received:
"Engineering has determined that this issue behaves as intended based on the following information:
Because C enums may have values added in future releases, or even have "private case" values used by the framework that are not included in the headers, there's no way to check whether a value provided in Swift is actually valid or invalid. Therefore,
init(rawValue:)
is obliged to produce a value just as a C cast would. There are discussions in the Swift Open Source project on how to improve this situation in later versions of Swift, but the initializer for MKMapType still won't return nil."
Thanks to Apple Engineering for this explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With