【发布时间】:2020-06-19 22:46:02
【问题描述】:
我有以下枚举并且它有效。但是,有没有一种方法可以简单地更改 Int 并使其成为 String ,然后直接分配?
下面是不是很罗嗦? Companies(rawValue: httpMethod.self.rawValue)! 与 Companies.stringValue 相比
如何调用以下命令来获取字符串值?
public enum Companies: String {
case oil = "OIL"
case tech = "TECH"
case government = "GOVERNMENT"
case restaurant = "RESTAURANT"
}
以下作品!
public enum Companies: Int {
case oil
case tech
case government
case restaurant
var stringValue: String {
switch self {
case .oil:
return "OIL"
case .tech:
return "TECH"
case .government:
return "GOVERNMENT"
case .restaurant:
return "RESTAURANT"
}
}
}
我可以直接拨打Companies.stringValue
【问题讨论】:
-
“但是为什么下面的方法不起作用?”。它确实有效。事实上,您甚至可以删除分配,它仍然有效。
-
对不起@matt,我已经解决了我的问题。我很抱歉。
-
this answer 怎么样:使用
enum Companies: CustomStringConvertible并添加var description: String而不是stringValue。 -
我还是不明白这一点。请提供真实的用例。
-
enum Companies: String, CustomStringConvertible {case oil, tech, government, restaurantpublic var description: String { rawValue.uppercased() }}
标签: swift