【问题标题】:Make enum that has a raw String type codable with Objective-C使具有原始字符串类型的枚举可使用 Objective-C 编码
【发布时间】:2023-01-28 01:31:18
【问题描述】:

我有一个可编码的枚举:

public enum MyEnum: String, Codable, Hashable, Sendable {
  case one = "ONE"
  case two = "TWO"

  public init(from decoder: Decoder) throws {
    let container = try decoder.singleValueContainer()
    let rawValue = try container.decode(RawValue.self)
    self = MyEnum(rawValue: rawValue) ?? .one
  }
}

但是,我现在需要使其与 objective-c 兼容。我知道我不能有String原始值,它必须是Int。我仍然需要它像以前一样兼容,因为它是从 JSON 创建的,JSON 是一个字符串而不是一个 Int。我该怎么做呢?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    好的,我想我想出了一个解决方案(如果我错了请纠正我!)

    public enum MyEnum: Int, Codable, Hashable, Sendable {
      case one
      case two
    
      enum InternalMyEnum: String, Codable {
        case one = "ONE"
        case two = "TWO"
      }
    
      public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
    
        switch self {
        case .one:
          try container.encode(InternalMyEnum.one.rawValue)
        case .two:
          try container.encode(InternalMyEnum.two.rawValue)
        }
      }
    
      public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let rawValue = try container.decode(String.self)
        let internalMyEnum = InternalMyEnum(rawValue: rawValue) ?? .one
        switch internalVariantType {
        case .one:
          self = .one
        case .one:
          self = .one
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多