/ / Czy w JSONDecoder w Swift 4, czy brakujące klucze mogą używać wartości domyślnej zamiast być opcjonalnymi właściwościami? - json, swift, swift4, kodowalny

W przypadku JSONDecoder w Swift 4, czy brakujące klucze mogą używać wartości domyślnej, zamiast być właściwościami opcjonalnymi? - json, swift, swift4, kodowalny

Swift 4 dodał nowy Codeable protokół. Kiedy używam JSONDecoder wydaje się, że wymaga wszystkich moich nie opcjonalnych właściwości Codeable klasy, aby mieć klucze w JSON lub zgłasza błąd.

Uczynienie opcjonalnymi każdej właściwości mojej klasy wydaje się niepotrzebnym kłopotem, ponieważ tak naprawdę chcę użyć wartości w pliku json lub wartości domyślnej. (Nie chcę, aby właściwość była zerowa.)

Czy jest jakiś sposób na zrobienie tego?

class MyCodable: Codable {
var name: String = "Default Appleseed"
}

func load(input: String) {
do {
if let data = input.data(using: .utf8) {
let result = try JSONDecoder().decode(MyCodable.self, from: data)
print("name: (result.name)")
}
} catch  {
print("error: (error)")
// `Error message: "Key not found when expecting non-optional type
// String for coding key "name""`
}
}

let goodInput = "{"name": "Jonny Appleseed" }"
let badInput = "{}"
load(input: goodInput) // works, `name` is Jonny Applessed
load(input: badInput) // breaks, `name` required since property is non-optional

Odpowiedzi:

44 dla odpowiedzi nr 1

Możesz wdrożyć init(from decoder: Decoder) metoda w swoim typie zamiast domyślnej implementacji:

class MyCodable: Codable {
var name: String = "Default Appleseed"

required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let name = try container.decodeIfPresent(String.self, forKey: .name) {
self.name = name
}
}
}

Istnieje również możliwość name stała właściwość (jeśli chcesz):

class MyCodable: Codable {
let name: String

required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let name = try container.decodeIfPresent(String.self, forKey: .name) {
self.name = name
} else {
self.name = "Default Appleseed"
}
}
}

lub

required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"
}

Wpisz swój komentarz: Z niestandardowym rozszerzeniem

extension KeyedDecodingContainer {
func decodeWrapper<T>(key: K, defaultValue: T) throws -> T
where T : Decodable {
return try decodeIfPresent(T.self, forKey: key) ?? defaultValue
}
}

możesz zaimplementować metodę init jako

required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeWrapper(key: .name, defaultValue: "Default Appleseed")
}

ale to nie jest dużo krótszy niż

    self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"