<分区>
如果标题丢失,我希望初始化返回 nil。
- 将
?
添加到init
会产生以下错误:
Non-failable initializer requirement 'init(from:)' cannot be satisfied by a failable initializer ('init?')
- 添加
if title == nil { return nil}
会产生以下错误:
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)
}
}