enum PostType: Decodable {
init(from decoder: Decoder) throws {
// What do i put here?
}
case Image
enum CodingKeys: String, CodingKey {
case image
}
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能完成这个?另外,让我说我改变了case这个:
case image(value: Int)
Run Code Online (Sandbox Code Playgroud)
如何使其符合Decodable?
编辑这是我的完整代码(不起作用)
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
}
Run Code Online (Sandbox Code Playgroud)
最终编辑 另外,它将如何处理这样的枚举?
enum PostType: Decodable {
case count(number: Int)
}
Run Code Online (Sandbox Code Playgroud)
vad*_*ian 207
它非常简单,只需使用String或Int隐式分配的原始值.
enum PostType: Int, Codable {
case image, blob
}
Run Code Online (Sandbox Code Playgroud)
image被编码到0并blob到1
要么
enum PostType: String, Codable {
case image, blob
}
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
pro*_*ero 83
Codable这个答案是类似于@Howard Lovatt的,但避免了创造一个PostTypeCodableForm结构,而是使用了KeyedEncodingContainer类苹果提供作为一个财产Encoder和Decoder,从而降低了样板.
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码适用于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)
Run Code Online (Sandbox Code Playgroud)
编辑:如果你觉得这样做很舒服,请看看@ marcprux的解决方案,它更简洁,更安全.
Tok*_*oka 27
.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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
以及如何在封闭结构中使用它:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
Sté*_*pin 17
要扩展@Tacka的答案,您也可以在枚举中添加一个原始的可表示值,并使用默认的可选构造函数来构建枚举,而不需要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
}
}
Run Code Online (Sandbox Code Playgroud)
它可以使用允许重构构造函数的自定义协议进行扩展:
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
}
Run Code Online (Sandbox Code Playgroud)
如果指定了无效的枚举值,它也可以很容易地扩展为抛出错误,而不是默认值.有关此更改的要点可在此处获取:https://gist.github.com/stephanecopin/4283175fabf6f0cdaf87fef2a00c8128.
使用Swift 4.1/Xcode 9.3编译和测试代码.
实际上,上面的答案确实很棒,但是它们缺少许多人在不断开发的客户端/服务器项目中需要的一些细节。我们开发了一个应用程序,而我们的后端随着时间的推移不断发展,这意味着一些枚举案例将改变这种演变。所以我们需要一个能够解码包含未知情况的枚举数组的枚举解码策略。否则解码包含数组的对象就会失败。
我所做的很简单:
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
}
}
Run Code Online (Sandbox Code Playgroud)
奖励:隐藏实现 > 使其成为一个集合
隐藏实现细节总是一个好主意。为此,您只需要多一点代码。关键是要符合DirectionsList以Collection使您的内部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)
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在 John Sundell 的这篇博文中阅读有关符合自定义集合的更多信息:https ://medium.com/@johnsundell/creating-custom-collections-in-swift-a344e25d0bb0
你可以做你想做的,但这有点牵扯:(
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)
Run Code Online (Sandbox Code Playgroud)
@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)
}
}
Run Code Online (Sandbox Code Playgroud)
这使编译器可以详尽地验证情况,也不会在编码值与键的期望值不匹配的情况下抑制错误消息。
| 归档时间: |
|
| 查看次数: |
44752 次 |
| 最近记录: |