swift - 如何使用那里的子函数获取枚举的 rawValue?
问题描述
我有一个定义如下的枚举。
enum PurchaseTimeType: Int,CaseIterable {
case ASAP, ThisMonth, NextMonth
func id() -> Int {
switch self {
case .ASAP:
return 1
case .ThisMonth:
return 2
case .NextMonth:
return 3
}
}
func title() -> String {
switch self {
case .ASAP:
return "ASAP"
case .ThisMonth:
return "This Month"
case .NextMonth:
return "Next Month"
}
}
}
我已经id
存储在一个变量中:
var id = 1
我怎样才能得到title()
那个id
?
解决方案
您将Int
id 分配给每个案例,如下所示:
enum PurchaseTimeType: Int, CaseIterable {
case asap = 1
case thisMonth = 2
case nextMonth = 3
// All above cases can also be written in one line, like so
// case asap = 1, thisMonth, nextMonth
var id: Int {
return self.rawValue
}
var title: String {
switch self {
case .asap:
return "ASAP"
case .thisMonth:
return "This Month"
case .nextMonth:
return "Next Month"
}
}
}
用法-1
let purchaseTime: PurchaseTimeType = .thisMonth
print(purchaseTime.id, ":", purchaseTime.title)
Usage-2:按 id 过滤
let id = 1
if let type = PurchaseTimeType.allCases.first(where: { $0.id == id } ) {
print("Title for \(id) is \(type.title)")
}
注意我从UPPERCASE更新了案例名称以遵循约定,每个案例都应该命名为lowerCamelCase,每个后续单词的第一个字母小写,大写字母。
推荐阅读
- reactjs - Recharts 不适用于带有 typescript 的 React
- scala - Scala如何在endsWith上使用正则表达式?
- reactjs - 即使 url 触发器没有改变,点击后运行 useEffect
- clojure - 试图在 Clojure 中创建一个空集
- c++ - 一一搭建CGAL Mesh_criteria
- scala - 铸造问题
- python - ttk notebook 帧数过多导致故障
- javascript - 为什么我的客户没有听到套接字 io 事件?
- ajax - 为什么来自 Ajax w XMLHttpRequest 的数据没有到达指定的 div id
- python - 打开pyxl。忽略具有样式但没有值的单元格