Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Enum in swift?

Tags:

ios

swift

in Objective-C this works fine

enter image description here

Can't compile this in Swift

enter image description here

Or

enter image description here

ALAuthorizationStatus definition in IOS SDK

enum ALAuthorizationStatus : Int {
    case NotDetermined // User has not yet made a choice with regards to this application
    case Restricted // This application is not authorized to access photo data.
    // The user cannot change this application’s status, possibly due to active restrictions
    //  such as parental controls being in place.
    case Denied // User has explicitly denied this application access to photos data.
    case Authorized // User has authorized this application to access photos data.
}
like image 819
Charlie Avatar asked Jun 20 '14 10:06

Charlie


People also ask

Can you compare string to enum?

To compare a string with an enum, extend from the str class when declaring your enumeration class, e.g. class Color(str, Enum): . You will then be able to compare a string to an enum member using the equality operator == . Copied!

What is difference between enum and enumeration in Swift?

Enumeration is a data type that allows you to define a list of possible values. An enum allows you to create a data type with those set of values so that they can be recognised consistently throughout your app.

What is enum in Swift?

In Swift, an enum (short for enumeration) is a user-defined data type that has a fixed set of related values. We use the enum keyword to create an enum. For example, enum Season { case spring, summer, autumn, winter } Here, Season - name of the enum.


1 Answers

The comparison operator == returns a Bool, not Boolean. The following compiles:

func isAuthorized() -> Bool {
    let status = ALAssetsLibrary.authorizationStatus()
    return status == ALAuthorizationStatus.Authorized
}

(Personally, I find the error messages from the Swift compiler sometimes confusing. In this case, the problem was not the arguments of ==, but the incorrect return type.)


Actually, the following should also compile due to the automatic type inference:

func isAuthorized() -> Bool {
    let status = ALAssetsLibrary.authorizationStatus()
    return status == .Authorized
}

But it fails with the compiler error "Could not find member 'Authorized'", unless you explicitly specify the type of the status variable:

func isAuthorized() -> Bool {
    let status:ALAuthorizationStatus = ALAssetsLibrary.authorizationStatus()
    return status == .Authorized
}

This could be a bug in the current Swift compiler (tested with Xcode 6 beta 1).

Update: The first version now compiles in Xcode 6.1.

like image 89
Martin R Avatar answered Nov 02 '22 23:11

Martin R