如何在Swift 4中创建可枚举的枚举?


156
enum PostType: Decodable {

    init(from decoder: Decoder) throws {

        // What do i put here?
    }

    case Image
    enum CodingKeys: String, CodingKey {
        case image
    }
}

我要完成什么呢?另外,可以说我将其更改case为:

case image(value: Int)

我该如何使它符合“可降解”?

EDit这是我的完整代码(无效)

let jsonData = """
{
    "count": 4
}
""".data(using: .utf8)!

        do {
            let decoder = JSONDecoder()
            let response = try decoder.decode(PostType.self, from: jsonData)

            print(response)
        } catch {
            print(error)
        }
    }
}

enum PostType: Int, Codable {
    case count = 4
}

最终编辑 另外,它将如何处理这样的枚举?

enum PostType: Decodable {
    case count(number: Int)
}

Answers:


262

这很简单,只需使用StringInt隐式分配的原始值即可。

enum PostType: Int, Codable {
    case image, blob
}

image被编码到0blob1

要么

enum PostType: String, Codable {
    case image, blob
}

image被编码到"image"blob"blob"


这是一个简单的示例如何使用它:

enum PostType : Int, Codable {
    case count = 4
}

struct Post : Codable {
    var type : PostType
}

let jsonString = "{\"type\": 4}"

let jsonData = Data(jsonString.utf8)

do {
    let decoded = try JSONDecoder().decode(Post.self, from: jsonData)
    print("decoded:", decoded.type)
} catch {
    print(error)
}

1
我尝试了您建议的代码,但是它不起作用。我已经编辑了代码以显示我要解码的JSON
swift nub

8
枚举不能单独编码/解码。它必须嵌入在结构中。我加了一个例子。
vadian

我将其标记为正确。但是以上问题的最后一部分没有得到回答。如果我的枚举看起来像这样怎么办?(如上编辑)
swift nub

如果您使用具有关联类型的枚举,则必须编写自定义编码和解码方法。请阅读编码和解码自定义类型
vadian

1
关于“不能单独枚举/枚举枚举。”,似乎可以在处解决iOS 13.3。我在iOS 13.3和中进行测试iOS 12.4.3,它们的行为有所不同。在之下iOS 13.3,可以仅对enum进行编码/解码。
AechoLiu

111

如何使具有关联类型的枚举符合 Codable

这个答案类似于@Howard Lovatt的答案,但是避免创建PostTypeCodableForm结构,而是使用Apple提供KeyedEncodingContainer类型作为and 的属性,从而减少了样板。EncoderDecoder

enum PostType: Codable {
    case count(number: Int)
    case title(String)
}

extension PostType {

    private enum CodingKeys: String, CodingKey {
        case count
        case title
    }

    enum PostTypeCodingError: Error {
        case decoding(String)
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        if let value = try? values.decode(Int.self, forKey: .count) {
            self = .count(number: value)
            return
        }
        if let value = try? values.decode(String.self, forKey: .title) {
            self = .title(value)
            return
        }
        throw PostTypeCodingError.decoding("Whoops! \(dump(values))")
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        switch self {
        case .count(let number):
            try container.encode(number, forKey: .count)
        case .title(let value):
            try container.encode(value, forKey: .title)
        }
    }
}

该代码在Xcode 9b3上对我有效。

import Foundation // Needed for JSONEncoder/JSONDecoder

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let decoder = JSONDecoder()

let count = PostType.count(number: 42)
let countData = try encoder.encode(count)
let countJSON = String.init(data: countData, encoding: .utf8)!
print(countJSON)
//    {
//      "count" : 42
//    }

let decodedCount = try decoder.decode(PostType.self, from: countData)

let title = PostType.title("Hello, World!")
let titleData = try encoder.encode(title)
let titleJSON = String.init(data: titleData, encoding: .utf8)!
print(titleJSON)
//    {
//        "title": "Hello, World!"
//    }
let decodedTitle = try decoder.decode(PostType.self, from: titleData)

我喜欢这个答案!作为一个说明,这个例子也反映在一个职位上objc.io有关使Either可编码
奔Leggiero

最佳答案
Peter Suwara

38

.dataCorrupted如果Swift 遇到未知的枚举值,将抛出错误。如果您的数据来自服务器,那么它可以随时向您发送未知的枚举值(错误服务器端,API版本中添加的新类型,并且您希望应用程序的先前版本能够妥善处理该案件等),您最好做好准备,并编写“防御风格”代码以安全地枚举枚举。

这是一个有或没有相关价值的方法示例

    enum MediaType: Decodable {
       case audio
       case multipleChoice
       case other
       // case other(String) -> we could also parametrise the enum like that

       init(from decoder: Decoder) throws {
          let label = try decoder.singleValueContainer().decode(String.self)
          switch label {
             case "AUDIO": self = .audio
             case "MULTIPLE_CHOICES": self = .multipleChoice
             default: self = .other
             // default: self = .other(label)
          }
       }
    }

以及如何在封闭结构中使用它:

    struct Question {
       [...]
       let type: MediaType

       enum CodingKeys: String, CodingKey {
          [...]
          case type = "type"
       }


   extension Question: Decodable {
      init(from decoder: Decoder) throws {
         let container = try decoder.container(keyedBy: CodingKeys.self)
         [...]
         type = try container.decode(MediaType.self, forKey: .type)
      }
   }

1
谢谢,您的答案更容易理解。
DazChong

1
谢谢,这个答案也对我有帮助。可以通过使您的枚举继承自String来改进它,然后您就不需要切换字符串了
Gobe 19'Jan

27

为了扩展@Toka的答案,您也可以在枚举中添加原始可表示的值,并使用默认的可选构造函数来构建不带switch:的枚举:

enum MediaType: String, Decodable {
  case audio = "AUDIO"
  case multipleChoice = "MULTIPLE_CHOICES"
  case other

  init(from decoder: Decoder) throws {
    let label = try decoder.singleValueContainer().decode(String.self)
    self = MediaType(rawValue: label) ?? .other
  }
}

可以使用允许重构构造函数的自定义协议对其进行扩展:

protocol EnumDecodable: RawRepresentable, Decodable {
  static var defaultDecoderValue: Self { get }
}

extension EnumDecodable where RawValue: Decodable {
  init(from decoder: Decoder) throws {
    let value = try decoder.singleValueContainer().decode(RawValue.self)
    self = Self(rawValue: value) ?? Self.defaultDecoderValue
  }
}

enum MediaType: String, EnumDecodable {
  static let defaultDecoderValue: MediaType = .other

  case audio = "AUDIO"
  case multipleChoices = "MULTIPLE_CHOICES"
  case other
}

如果指定了无效的枚举值,也可以很容易地扩展它以引发错误,而不是默认值。可以在此处找到具有此更改的要点:https : //gist.github.com/stephanecopin/4283175fabf6f0cdaf87fef2a00c8128
该代码使用Swift 4.1 / Xcode 9.3进行了编译和测试。


1
这就是我要寻找的答案。
内森·霍瑟尔顿

7

@proxpero响应的一个变体是简短的,将解码器表述为:

public init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    guard let key = values.allKeys.first else { throw err("No valid keys in: \(values)") }
    func dec<T: Decodable>() throws -> T { return try values.decode(T.self, forKey: key) }

    switch key {
    case .count: self = try .count(dec())
    case .title: self = try .title(dec())
    }
}

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    switch self {
    case .count(let x): try container.encode(x, forKey: .count)
    case .title(let x): try container.encode(x, forKey: .title)
    }
}

这使编译器可以详尽地验证情况,并且在编码值与键的期望值不匹配的情况下,也不会抑制错误消息。


我同意这会更好。
proxpero

6

实际上,以上答案确实很棒,但它们却缺少一些细节,这些细节是持续开发的客户端/服务器项目中许多人需要的。我们在开发应用程序的同时,后端会随着时间的推移不断发展,这意味着某些枚举案例将改变这种发展。因此,我们需要一种枚举解码策略,该策略能够解码包含未知情况的枚举数组。否则,解码包含数组的对象将完全失败。

我所做的很简单:

enum Direction: String, Decodable {
    case north, south, east, west
}

struct DirectionList {
   let directions: [Direction]
}

extension DirectionList: Decodable {

    public init(from decoder: Decoder) throws {

        var container = try decoder.unkeyedContainer()

        var directions: [Direction] = []

        while !container.isAtEnd {

            // Here we just decode the string from the JSON which always works as long as the array element is a string
            let rawValue = try container.decode(String.self)

            guard let direction = Direction(rawValue: rawValue) else {
                // Unknown enum value found - ignore, print error to console or log error to analytics service so you'll always know that there are apps out which cannot decode enum cases!
                continue
            }
            // Add all known enum cases to the list of directions
            directions.append(direction)
        }
        self.directions = directions
    }
}

奖励:隐藏实现>使其成为集合

隐藏实现细节始终是一个好主意。为此,您只需要多一点代码。关键是要符合DirectionsListCollection使您的内部list阵列私人:

struct DirectionList {

    typealias ArrayType = [Direction]

    private let directions: ArrayType
}

extension DirectionList: Collection {

    typealias Index = ArrayType.Index
    typealias Element = ArrayType.Element

    // The upper and lower bounds of the collection, used in iterations
    var startIndex: Index { return directions.startIndex }
    var endIndex: Index { return directions.endIndex }

    // Required subscript, based on a dictionary index
    subscript(index: Index) -> Element {
        get { return directions[index] }
    }

    // Method that returns the next index when iterating
    func index(after i: Index) -> Index {
        return directions.index(after: i)
    }
}

您可以在John Sundell的此博客文章中了解有关符合自定义集合的更多信息:https ://medium.com/@johnsundell/creating-custom-collections-in-swift-a344e25d0bb0


5

你可以做你想做的,但是有点麻烦:(

import Foundation

enum PostType: Codable {
    case count(number: Int)
    case comment(text: String)

    init(from decoder: Decoder) throws {
        self = try PostTypeCodableForm(from: decoder).enumForm()
    }

    func encode(to encoder: Encoder) throws {
        try PostTypeCodableForm(self).encode(to: encoder)
    }
}

struct PostTypeCodableForm: Codable {
    // All fields must be optional!
    var countNumber: Int?
    var commentText: String?

    init(_ enumForm: PostType) {
        switch enumForm {
        case .count(let number):
            countNumber = number
        case .comment(let text):
            commentText = text
        }
    }

    func enumForm() throws -> PostType {
        if let number = countNumber {
            guard commentText == nil else {
                throw DecodeError.moreThanOneEnumCase
            }
            return .count(number: number)
        }
        if let text = commentText {
            guard countNumber == nil else {
                throw DecodeError.moreThanOneEnumCase
            }
            return .comment(text: text)
        }
        throw DecodeError.noRecognizedContent
    }

    enum DecodeError: Error {
        case noRecognizedContent
        case moreThanOneEnumCase
    }
}

let test = PostType.count(number: 3)
let data = try JSONEncoder().encode(test)
let string = String(data: data, encoding: .utf8)!
print(string) // {"countNumber":3}
let result = try JSONDecoder().decode(PostType.self, from: data)
print(result) // count(3)

有趣的骇客
Roman Filippov
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.