枚举原始值构造函数忽略大小写


enum DocumentType : String
{
    case
    Any = "Any",
    DL = "DL",
    Passport = "Passport",
    Invalid
}

我正在使用这样的原始值构造函数

if let d = DocumentType(rawValue: type) {

解析来自服务器的任何内容。

现在,假设服务器端调光灯泡将 DL 更改为 Dl 服务器端 ->解析器中断默认为无效。

是否有Windows开发人员校对解析器的规定没有手动写一个长,否则黛西?白痴在 JSON 中更改键的大小写也有同样的问题。需要某种方法来以一种不太好的开发人员抵抗方式读取 JSON。谢谢。

我认为你不能忽略大小写,但你可以创建一个初始化器来防止你的特定问题,而没有一连串的if/else语句:

enum DocumentType : String
{
    case
    Any = "Any",
    DL = "DL",
    Passport = "Passport",
    Invalid
    init?(raw:String) {
        let str = raw.characters.count > 2 ?  raw.capitalizedString : raw.uppercaseString
        if let d = DocumentType(rawValue: str) {
            self = d
        }
        else {
            return nil
        }
    }
}
if let d = DocumentType(raw: "ANY") {
    print("success!")
}
适用于所有

相关枚举的通用扩展。枚举必须遵守StringCaseIterable协议才能正常工作。

import Foundation
extension CaseIterable where Self:RawRepresentable, RawValue == String  {
    init?(rawValueIgnoreCase: RawValue) {
        if let caseFound = Self.allCases.first(where: { $0.rawValue.caseInsensitiveCompare(rawValueIgnoreCase) == .orderedSame }) {
            self = caseFound
        } else {
            self.init(rawValue: rawValueIgnoreCase)
        }
    }
}
enum FooBar: String, CaseIterable {
    case foo
    case bar = "BAR"
}
let foo = FooBar(rawValueIgnoreCase: "foo")
let FOO = FooBar(rawValueIgnoreCase: "FOO")
let FoO = FooBar(rawValueIgnoreCase: "FoO")
let bar = FooBar(rawValueIgnoreCase: "bar")
let Bar = FooBar(rawValueIgnoreCase: "Bar")
let BAR = FooBar(rawValueIgnoreCase: "BAR")
let oops = FooBar(rawValueIgnoreCase: "oops") // nil

我们可以通过在初始化枚举时使用更改大小写来做到这一点。

 enum DocumentType : String {
    case any = "ANY"
    case dl = "DL"
    case passport = "PASSPORT"
    case invalid = "INVALID"
    //If you want to display status in UI define your display name
    var documentDisplayType: String {
     switch self  {
       case .any:
            return "Any"
       case .dl:
            return "Driving License"
       case .passport:
            return "Passport"
       case invalid:
            return "Not proper document"
    }
}

初始化时,使用 uppercased() 函数将 repose 文档类型更改为大写。

 let type = "Dl"
 let docType = DocumentType(rawValue: type.uppercased())
 print(docType.documentDisplayType) // Prints DL

最新更新