[英]Return the same raw value for unknown enum
我想为未知枚举返回相同的值,
我在我的代码中定义了以下枚举,
public enum Airport: String {
case munich = "MUN_T01"
case sanFrancisco = "SANF_T02"
case singapore = "SP_T03"
public var name: String {
switch self {
case .munich:
return "Munich"
case .sanFrancisco:
return "San Francisco"
case .singapore:
return "Singapore"
}
}
每当我调用上述枚举时,它都可以正常工作
var airportName = Airport(rawValue: "MUN_T01")
print("Airport Name: ", airportName) // munich
print("Airport Code: ", airportName.rawValue) // MUN_T01
现在我想为其他/未知场景覆盖相同的内容,例如,
var unknownAirportName = Airport(rawValue: "Test_T01")
,
应打印unknown
或other
当我打印unknownAirportName
变量,
如果我打印unknownAirportName.rawValue
,它应该打印Test_T01
我能够得到直到其他/未知情况,但我无法打印通过的相同值(Test_T01)。 有什么帮助吗?
考虑用原始值替换 enum 以使用关联的值进行枚举,然后您可以确定已知和未知的情况,例如:
public enum Airport {
case airport(name: String, code: String)
case unknown(code: String)
static let airports = [
Self.airport(name: "Munich", code: "MUN_T01"),
Self.airport(name: "San Francisco", code: "SANF_T02"),
Self.airport(name: "Singapore", code: "SP_T03")
]
var name: String {
if case let .airport(name, _) = self {
return name
}
return "Unknown"
}
var code: String {
switch self {
case let .airport(_, code):
return code
case let .unknown(code):
return code
}
}
static func airport(code: String) -> Airport {
if let item = Self.airports.first(where: { $0.code == code }) {
return item
}
return unknown(code: code)
}
}
let airport = Airport.airport(code: "MUN_T01")
print("Airport:", airport.name, airport.code) // Airport: Munich MUN_T01
let airport2 = Airport.airport(code: "NONE")
print("Airport:", airport2.name, airport2.code) // Airport: Unknown NONE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.