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.

链接地址: http://www.djcxy.com/p/21164.html

上一篇: 如何打开指定大小的Chrome浏览器

下一篇: 如何在swift中比较Enum?