简体   繁体   中英

How to compare Enum in swift?

in Objective-C this works fine

在此输入图像描述

Can't compile this in Swift

在此输入图像描述

Or

在此输入图像描述

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.
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM