Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift using if on an enum resulting in error not convertible to '_ArrayCastKind'

Tags:

xcode

swift

I'm using Beta 3 of xcode 6, and I am having a problem doing a simple if statement against an enum passed into an argument of a closure. Here is the simple enum definition:

enum FLSTeslaLoginStatus {
    case LoggedOut
    case LoggedIn
    case LoggingIn
    case LoginFailed(NSData!, NSHTTPURLResponse!, NSError)
}

And the code with the error is:

enter image description here

As you can see the switch statement works fine, but the if check is resulting in the error. This is just some test code so I won't normally have a switch and an if statement, but I'm trying to figure out what's wrong with the if statement. I'm thinking it is a compiler bug.

This is supported in Swift 2.0 with the use of "if case".

like image 693
Tod Cunningham Avatar asked Jul 10 '14 03:07

Tod Cunningham


People also ask

Should enum be capitalized in Swift?

The name of an enum in Swift should follow the PascalCase naming convention in which the first letter of each word in a compound word is capitalized.

What is raw value or associated value in enum?

The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so.

How do I make an enum iterable?

To enable it, all you need to do is make your enum conform to the CaseIterable protocol and at compile time Swift will automatically generate an allCases property that is an array of all your enum's cases, in the order you defined them.


2 Answers

Swift 2.x allows this via the if case pattern match: https://www.natashatherobot.com/swift-2-pattern-matching-with-if-case/

if case let .LoggedIn(name,password) = status  {
   print( "\(name) Logged in!" )
}
like image 87
Tod Cunningham Avatar answered Sep 20 '22 07:09

Tod Cunningham


At this time (iOS8 Beta 4) it seems you need to fully-quality the enum value when doing an == comparison.

OK:

if (taskSortOrder == TaskSortOrder.Name) {
    ...
}

Error: "TaskSortOrder' is not convertible to 'Selector'"

if (taskSortOrder == .Name) {
    ...
}
like image 28
Michael Peterson Avatar answered Sep 17 '22 07:09

Michael Peterson