简体   繁体   中英

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. Because you have declared init(from decoder:) you do not get the memberwise initialiser.

You can add your own memberwise initialiser. In fact, Xcode can do this for you.

Click on the name of your struct and then right-click and select "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? property.

add this to Student :

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

and use it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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