簡體   English   中英

Objective-C 外部常量屬性到 Swift 枚舉的轉換

[英]Objective-C External constant property to Swift enum conversion

我想使用Contacts框架CNLabeledValueCNPhoneNumber類型進行枚舉,其定義為:

// Generic labels
CONTACTS_EXTERN NSString * const CNLabelHome    NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelWork    NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelSchool  NS_AVAILABLE(10_15, 13_0);
CONTACTS_EXTERN NSString * const CNLabelOther   NS_AVAILABLE(10_11, 9_0);

我做了這樣的事情:

enum CNLabeledValueType: String {
    case home
    case work
    case school
    case other

    var rawValue: String {
        switch self {
        case .home:
            return CNLabelHome
        case .work:
            return CNLabelHome
        case .school:
            return CNLabelSchool
        default:
            return CNLabelOther
        }
    }
}

但我認為我仍然需要將枚舉映射到正確的運行時字符串,我是否還需要以某種方式覆蓋枚舉的初始化?

我想要實現的結果與這可能實現的結果相同:

enum CNLabeledValueType: String {
    case home = CNLabelHome
    case work = CNLabelWork
    case school = CNLabelSchool
    case other = CNLabelOther
}

但這是不可能的,因為 Swift 枚舉要求“枚舉的原始值必須是字符串文字”,正如編譯器所抱怨的那樣。 那么有沒有辦法使用計算屬性來制作類似的東西,以便可以按案例字符串進行切換,並在運行時為每個案例獲取正確的字符串計算值?

您可以像這樣實現init(rawValue:)

init?(rawValue: String) {
    switch rawValue {
    case CNLabelHome:
        self = .home
    case CNLabelWork:
        self = .work
    case CNLabelSchool:
        self = .school
    case CNLabelOther:
        self = .other
    default:
        return nil
    }
}

另請注意,您在rawValue實現中有一個錯字。 第二種情況應該返回CNLabelWork 我還建議不要在原始值 switch 語句中使用default: ::

var rawValue: String {
    switch self {
    case .home:
        return CNLabelHome
    case .work:
        return CNLabelWork
    case .school:
        return CNLabelSchool
    case .other:
        return CNLabelOther
    }
}

這樣,當您要添加新標簽時,switch 語句處會出現錯誤,因此您不會忘記添加另一個案例。

暫無
暫無

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

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