加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 对Codable的Explit一致性消除了结构上的成员初始化器生

发布时间:2020-12-14 02:26:38 所属栏目:百科 来源:网络整理
导读:鉴于: struct Foo { let bar: Bar} 我得到一个方便的初始化器使用: 让foo = Foo(bar:Bar()) 但是如果Bar本身不是Codable,或者由于某些其他原因我需要在Foo上显式实现Codable,那么便利的成员初始化器不再存在: struct Foo: Codable { init(from decoder:
鉴于:
struct Foo {
    let bar: Bar
}

我得到一个方便的初始化器使用:

让foo = Foo(bar:Bar())

但是如果Bar本身不是Codable,或者由于某些其他原因我需要在Foo上显式实现Codable,那么便利的成员初始化器不再存在:

struct Foo: Codable {

    init(from decoder: Decoder) throws {

    }

    func encode(to encoder: Encoder) throws {

    }

    let bar: Bar
}

我得到:

让foo = Foo(bar:Bar())

Incorrect argument label in call (have ‘bar:’,expected ‘from:’)

是否有可能在这里拥有两全其美?

您可以在扩展中实现Codable一致性.

在扩展中添加任何struct初始化程序时,不会删除成员初始值设定项.

struct MyStruct {
    var name: String
}
extension MyStruct: Codable {} // preserves memberwise initializer

MyStruct(name: "Tim")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读