【问题标题】:Return the same raw value for unknown enum为未知枚举返回相同的原始值
【发布时间】:2020-12-14 18:58:31
【问题描述】:

我想为未知枚举返回相同的值,

我在我的代码中定义了以下枚举,

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"),

当我打印 unknownAirportName 变量时应该打印 unknownother

如果我打印unknownAirportName.rawValue,它应该打印Test_T01

在其他/未知情况之前我能够得到,但我无法打印通过的相同值 (Test_T01)。有什么帮助吗?

【问题讨论】:

  • Airport(rawValue: "Test_T01") 应该生成一个nil 项目,因为“默认代码”无法解析结果。相反,您需要提供自己的解析器代码,以便在找不到指定文本的匹配项时,可以返回 unknown 结果
  • 您也可以为case other = "Other" 等其他场景创建一个案例,然后执行类似var unknownAirportName = Airport(rawValue: "Test_T01") ?? Airport.other 的操作

标签: ios swift enums swift3


【解决方案1】:

考虑将 enum 替换为原始值以 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    相关资源
    最近更新 更多