简体   繁体   English

swift如何初始化可编码对象

[英]swift how to initialize a Codable Object

I want to initialize a Codable Object, for example:我想初始化一个可编码对象,例如:

struct Student: Codable {
  let name: String?
  let performance: String?

  enum CodingKeys: String, CodingKey {
        case name, performance
    }

  init(from decoder: Decoder) {
        let container = try? decoder.container(keyedBy: CodingKeys.self)
        name = try? container?.decodeIfPresent(String.self, forKey: .name)
        performance = try? container?.decodeIfPresent(TextModel.self, forKey: .performance)
}

I want to initialize a Student Instance like this, but it says "Argument type 'String' does not conform to expected type 'Decoder', or "Incorrect argument label in call (have 'name:', expected 'from:')" :我想像这样初始化一个学生实例,但它说“参数类型'字符串'不符合预期的类型'解码器',或“调用中的参数标签不正确(有'名称:',预期'来自:')” :

var Student = Student(name: "Bruce", perfdormace: "A+")

Swift structs get a memberwise initialiser by default, as long as you don't declare any other initialiser.只要您不声明任何其他初始化程序,Swift 结构默认会获得一个成员初始化程序。 Because you have declared init(from decoder:) you do not get the memberwise initialiser.因为你已经声明init(from decoder:)你没有得到成员初始化器。

You can add your own memberwise initialiser.您可以添加自己的成员初始化程序。 In fact, Xcode can do this for you.事实上,Xcode 可以为你做到这一点。

Click on the name of your struct and then right-click and select "Refactor->Generate Memberwise Initialiser"单击结构的名称,然后右键单击并选择“Refactor->Generate Memberwise Initialiser”

Alternatively, see if you can eliminate the init(from decoder:) - It looks pretty close to the initialiser that Codable will give you for free, and it also doesn't look correct - You are assigning a TextModel to a String?或者,看看您是否可以消除init(from decoder:) - 它看起来非常接近Codable将免费提供给您的初始化程序,而且看起来也不正确 - 您正在将TextModel分配给String? property.财产。

add this to Student :将此添加到Student

init(name: String?, performance: String?) {
    self.name = name
    self.performance = performance
}

and use it like this:并像这样使用它:

 var student = Student(name: "Bruce", performance: "A+")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM