Avatar
↓みたいな JSON 型が標準で提供されると便利そう。自由なフォーマットの JSON をコード側で扱いたいとき。 JSONSerialization と比べるとパフォーマンス悪いけど。 enum JSON { case number(Double) case boolean(Bool) case string(String) case array([JSON]) case object([String: JSON]) case null } extension JSON: Codable { init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let value = try? container.decode(Double.self) { self = .number(value) } else if let value = try? container.decode(Bool.self) { self = .boolean(value) } else if let value = try? container.decode(String.self) { self = .string(value) } else if let value = try? container.decode([JSON].self) { self = .array(value) } else if let value = try? container.decode([String: JSON].self) { self = .object(value) } else if container.decodeNil() { self = .null } else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Failed to interpret as a JSON value.", underlyingError: nil)) } } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .number(let value): try container.encode(value) case .boolean(let value): try container.encode(value) case .string(let value): try container.encode(value) case .array(let value): try container.encode(value) case .object(let value): try container.encode(value) case .null: try container.encodeNil() } } }
12:40 AM
let json = "[true]".data(using: .utf8)! let decoded = try JSONDecoder().decode(JSON.self, from: json) // .array(.boolean(true))