Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Enums Swift-在switch语句中使用enum_Enums_Swift_Switch Statement - Fatal编程技术网

Enums Swift-在switch语句中使用enum

Enums Swift-在switch语句中使用enum,enums,swift,switch-statement,Enums,Swift,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:

我得到这个错误:

'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 {
    // ...
  }
}

我在最近的一个应用程序中处理这种情况的方法是使用完全由静态成员组成的结构,而不是枚举-部分原因是我有更多的信息与每个选项关联,部分原因是我厌倦了必须调用
toRaw()
fromRaw()
everyplace,部分原因是(如您的示例所示,您已经发现)当您无法循环遍历或获取案例的完整列表时,枚举将失去其优势

所以,我所做的是:

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]!
    }
}
现在,当我们来到
cellforrowatinexpath
时,我可以这样说:

    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
    }

本质上,我只是使用了两个结构作为名称空间,增加了一些智能。我并不是说这比你正在做的更好,它们都是非常快的。这只是另一个要考虑的想法。

简单的答案是,不要试图说谎类型;索引路径是INT,不是猫。但是,不要让这阻止你;你是什么?重做是非常快的,你应该继续沿着这条路走下去。很酷。GoZeNo在技术上回答了这个问题。但是我想我会做一些这样的重构,这样我就不必继续输入字符串。+1你可能想至少考虑一个字符串的枚举,而不是一个int的枚举,一个静态函数返回一个案例列表,类似于我正在做的。您将如何执行类似于
let style=Styles.Animals?
我得到“NSString不是样式的子类型”的操作?您失去了我。也许可以问一个完整的单独问题?这样您可以显示您的代码。。。