I would like the initialization to return nil in case title is missing.
? to init produces the following error:Non-failable initializer requirement 'init(from:)' cannot be satisfied by a failable initializer ('init?')
if title == nil { return nil} produces the following error:Only a failable initializer can return 'nil'
class ClassA: Decodable {
let title: String
let subtitle: String?
private enum CodingKeys: String, CodingKey {
case title
case subtitle
}
required init(from decoder: Decoder) throws {
// changing the signature to:
// required init?(from decoder: Decoder) throws
// produced:
// Non-failable initializer requirement 'init(from:)' cannot be satisfied by a failable initializer ('init?')
let container = try decoder.container(keyedBy: CodingKeys.self)
guard let theTitle = try container.decode(String.self, forKey: .title) else {
return nil // Only a failable initializer can return 'nil'
}
title = theTitle
subtitle = try? container.decode(String.self, forKey: .subtitle)
}
}
Failable initializer is not available for Codable types for now.
Also, I don't think a failable initializer is even required for this case. You will automatically get nil for object if title is not available in the JSON since it is not an optional.
And, there is no requirement of enum CodingKeys because the property names match the JSON keys as per your code.
Neither init(from:) implementation is required because you're not doing any specific parsing here.
Keep the model as clean as possible like,
class ClassA: Decodable {
let title: String
let subtitle: String?
}
You can parse your JSON response using,
let classA = try? JSONDecoder().decode(ClassA.self, from: data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With