-2

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+")
malcopolocei
  • 123
  • 1
  • 9

2 Answers2

4

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.

Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • I had the same issue working with multiple data types, I had to use a decoder. This worked flawlessly when initializing my own object:) – ibyte Jul 18 '23 at 09:41
1

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