【问题标题】:Swift - using enum in switch statementSwift - 在 switch 语句中使用枚举
【发布时间】:2014-07-20 17:45:49
【问题描述】:

我收到此错误:

'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;
    }

我该如何解决这个错误?

【问题讨论】:

  • 简单的答案是,不要试图在类型上撒谎; indexPath.row 是一个 Int,而不是一个 Cat。但是,不要让这阻止你;你正在做的事情非常迅速,你应该继续沿着这条路走下去。非常好。

标签: enums swift switch-statement


【解决方案1】:

使用Cat.fromRaw(indexPath.row) 获取枚举。

因为fromRaw() 的返回值是一个可选,所以像这样使用它:

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

【讨论】:

    【解决方案2】:

    我在最近的一个应用程序中处理这种情况的方法是使用完全由静态成员组成的 Struct,而不是 Enum - 部分原因是我有更多信息可以与每个选项相关联,部分原因是我得到了厌倦了在每个地方都打电话给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
        }
    

    基本上我只是将这两个结构用作命名空间,并增加了一些智能。我并不是说这比你正在做的更好;他们都非常敏捷。这只是另一个需要考虑的想法。

    【讨论】:

    • 酷。 GoZoner 从技术上回答了这个问题。但我想我会像这样进行一些重构,这样我就不必继续输入字符串了。 +1
    • 您可能需要考虑至少一个字符串枚举而不是整数枚举,以及一​​个返回案例列表的静态函数,类似于我正在做的事情。
    • 你会怎么做类似let style = Styles.Animals? 我得到“NSString 不是样式的子类型”
    • 你失去了我。问一个完全不同的问题,也许?这样您就可以显示您的代码...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    相关资源
    最近更新 更多