ios - 可解码类的失败初始化器

标签 ios swift codable decodable

<分区>

如果标题丢失,我希望初始化返回 nil。

  1. ? 添加到 init 会产生以下错误:

Non-failable initializer requirement 'init(from:)' cannot be satisfied by a failable initializer ('init?')

  1. 添加 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)
   }
}

最佳答案

Failable initializer 目前不适用于 Codable 类型。

此外,我认为这种情况下甚至不需要可失败初始化器。如果titleJSON 中不可用,您将自动获得对象的nil,因为它不是可选

而且,不需要enum CodingKeys,因为属性名称根据您的代码匹配JSON 键

init(from:) 实现都不是必需的,因为您没有在此处进行任何特定的解析。

尽可能保持模型干净,例如,

class ClassA: Decodable {
    let title: String
    let subtitle: String?
}

您可以使用以下方式解析您的JSON 响应

let classA = try? JSONDecoder().decode(ClassA.self, from: data)

关于ios - 可解码类的失败初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56833322/

相关文章:

swift - 将无效的 URL 解码为 nil

iphone - 如何使用使用 Interface Builder 创建的 nib 文件加载 UIView

ios - 添加滤镜时,照片被拉伸(stretch)

ios - i386 架构的 undefined symbol (是的,再一次......)

ios - 使用 RxSwift,如何根据有效文本启用 UIButton?

ios - 错误 : Cannot assign value of type '[Item]' to type '[String]'

swift - Generic Decodable 无需解码

ios - 带有文本长度计数器的 UITextField

ios - NSPredicate 格式问题

json - 从 JSON 数据解码/编码混合对象数组