iosswiftxcodecodabledecoder

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

Solution

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