简体   繁体   English

如何在迅捷中比较Enum?

[英]How to compare Enum in swift?

in Objective-C this works fine 在Objective-C中这很好用

在此输入图像描述

Can't compile this in Swift 无法在Swift中编译它

在此输入图像描述

Or 要么

在此输入图像描述

ALAuthorizationStatus definition in IOS SDK IOS SDK中的ALAuthorizationStatus定义

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 . 比较运算符==返回Bool ,而不是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.) (就个人而言,我发现来自Swift编译器的错误消息有时令人困惑。在这种情况下,问题不是==的参数,而是错误的返回类型。)


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: 但它失败了编译器错误“找不到成员'授权'” ,除非您明确指定status变量的类型:

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). 这可能是当前Swift编译器中的一个错误(使用Xcode 6 beta 1测试)。

Update: The first version now compiles in Xcode 6.1. 更新:第一个版本现在在Xcode 6.1中编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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