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