簡體   English   中英

Swift - 在switch語句中使用enum

[英]Swift - using enum in switch statement

我收到此錯誤:

'NSNumber' is not a subtype of Cat

這是代碼:

enum Cat:Int {
    case Siamese = 0
    case Tabby
    case Fluffy
}

let cat = indexPath.row as Cat
    switch cat {
    case .Siamese:
        //do something
        break;
    case .Tabby:
        //do something else
        break;
    case .Fluffy:

        break;
    }

我該如何解決這個錯誤?

使用Cat.fromRaw(indexPath.row)獲取枚舉。

因為fromRaw()的返回值是可選的 ,所以使用它如下:

if let cat = Cat.fromRaw (indexPath.row) {
  switch cat {
    // ...
  }
}

我在最近的應用程序中處理同樣情況的方式是使用完全由靜態成員組成的Struct而不是Enum - 部分原因是因為我有更多信息與每個選項相關聯,部分原因是因為我厭倦了在toRaw()調用toRaw()fromRaw() ,部分原因是(正如你的例子所示,你發現)當事實證明你無法循環或獲得一個完整的列表時,Enum失去了它的優勢。案例。

所以,我做的是這樣的:

struct Sizes {
    static let Easy = "Easy"
    static let Normal = "Normal"
    static let Hard = "Hard"
    static func sizes () -> [String] {
        return [Easy, Normal, Hard]
    }
    static func boardSize (s:String) -> (Int,Int) {
        let d = [
            Easy:(12,7),
            Normal:(14,8),
            Hard:(16,9)
        ]
        return d[s]!
    }
}

struct Styles {
    static let Animals = "Animals"
    static let Snacks = "Snacks"
    static func styles () -> [String] {
        return [Animals, Snacks]
    }
    static func pieces (s:String) -> (Int,Int) {
        let d = [
            Animals:(11,110),
            Snacks:(21,210)
        ]
        return d[s]!
    }
}

現在,當我們到達cellForRowAtIndexPath我可以這樣說:

    let section = indexPath.section
    let row = indexPath.row
    switch section {
    case 0:
        cell.textLabel.text = Sizes.sizes()[row]
    case 1:
        cell.textLabel.text = Styles.styles()[row]
    default:
        cell.textLabel.text = "" // throwaway
    }

本質上我剛剛使用了兩個Structs作為名稱空間,並增加了一些智能。 我不是說這比你正在做的更好; 他們都非常迅速。 這只是另一個想法。

暫無
暫無

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

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