Home > Net >  swift how to initialize a Codable Object
swift how to initialize a Codable Object

Time:07-14

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 ")

CodePudding user response:

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.

CodePudding user response:

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 ")
  • Related