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
Swift:Enum case不是类型为';字符串';强制使用原始值_Swift_Enums - Fatal编程技术网

Swift:Enum case不是类型为';字符串';强制使用原始值

Swift:Enum case不是类型为';字符串';强制使用原始值,swift,enums,Swift,Enums,我有字符串枚举: enum Country:String { case France case Germany case UnitedStates } 但取决于uibutton restorationIdentifier,我想做点什么 我有一个行动: @IBAction func countrySelection(_ sender: UIButton) { guard let selection:String = sender.restorationIdenti

我有字符串枚举:

enum Country:String {
    case France
    case Germany
    case UnitedStates
}
但取决于uibutton restorationIdentifier,我想做点什么

我有一个行动:

@IBAction func countrySelection(_ sender: UIButton) {
    guard let selection:String = sender.restorationIdentifier else { return}
    switch selection {
    case Country.France:

    default:
        return
    }
}
但我在这一行中发现了一个错误:

Enum case'France'不是'String'类型的成员。

代码行:

案例国家。法国:

我可以修复将该行更改为以下内容的错误:

case Country.France.rawValue

但我的问题是,为什么我需要或强制使用原始值


非常感谢您的帮助。

您正在尝试将
字符串
国家
值进行比较。他们不是同一类型的。如您所述,您可以将
开关
案例
更改为
字符串
Country.France.rawValue

或者,您可以将
字符串
转换为
国家/地区
值:

@IBAction func countrySelection(_ sender: UIButton) {
    guard let selection = sender.restorationIdentifier else { return }
    guard let country = Country(rawValue: selection)

    switch country {
    case .France:
        // handle France
    default:
        return
    }
}

注意:这不是restorationIdentifier的真正用途。

您试图将
字符串
国家/地区
值进行比较。他们不是同一类型的。如您所述,您可以将
开关
案例
更改为
字符串
Country.France.rawValue

或者,您可以将
字符串
转换为
国家/地区
值:

@IBAction func countrySelection(_ sender: UIButton) {
    guard let selection = sender.restorationIdentifier else { return }
    guard let country = Country(rawValue: selection)

    switch country {
    case .France:
        // handle France
    default:
        return
    }
}

注意:这不是restorationIdentifier的真正用途。

我不想在按钮上使用标记。但是,除了设置
恢复标识符
,还有另一种设置ID的方法?使用
标记
是经批准的方法。你可以使你的enum
Int
为基础,并使用标记值。有些人使用按钮的当前字符串,但这不是一个好的做法,因为你的应用程序可能会被本地化,从而更改按钮文本。我不想对按钮使用标记。但是,除了设置
恢复标识符
,还有另一种设置ID的方法?使用
标记
是经批准的方法。你可以使你的enum
Int
为基础并使用标记值。有些人使用按钮的当前字符串,但这不是一个好的做法,因为你的应用程序可能会本地化,从而更改按钮文本。