Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum initialized with a non-existent rawValue does not fail and return nil

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?

like image 358
Georg Avatar asked Oct 31 '17 11:10

Georg


People also ask

Can we initialize enum in Swift?

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.

What is rawValue in Swift?

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.

What is Rawrepresentable?

A type that can be converted to and from an associated raw value.

Can enum have stored property?

enum s do have stored type properties - i.e., static properties. They don't have stored instance properties.


1 Answers

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.

like image 145
Georg Avatar answered Oct 04 '22 20:10

Georg