簡體   English   中英

如何在迅捷中比較Enum?

[英]How to compare Enum in swift?

在Objective-C中這很好用

在此輸入圖像描述

無法在Swift中編譯它

在此輸入圖像描述

要么

在此輸入圖像描述

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

比較運算符==返回Bool ,而不是Boolean 以下編譯:

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

(就個人而言,我發現來自Swift編譯器的錯誤消息有時令人困惑。在這種情況下,問題不是==的參數,而是錯誤的返回類型。)


實際上,由於自動類型推斷 ,還應編譯以下內容

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

但它失敗了編譯器錯誤“找不到成員'授權'” ,除非您明確指定status變量的類型:

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

這可能是當前Swift編譯器中的一個錯誤(使用Xcode 6 beta 1測試)。

更新:第一個版本現在在Xcode 6.1中編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM