鉴于:
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")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。