Hi, I got to day 51 of SwiftUI and I have a query. see with this initialiser, the function parameter names MUST be from (external parameter name) decoder (internal parameter name), changing 'from' to any other names won't work. I understand the deocder name has to be decoder because its used inside the initialiser. but why does the external parameter name has to be 'from' for the initialiser to work?
required init (from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
type = try container.decode(String.self, forKey: .type)
quantity = try container.decode(Int.self, forKey: .quantity)
extraFrosting = try container.decode(Bool.self, forKey: .extraFrosting)
addSprinkles = try container.decode(Bool.self, forKey: .addSprinkles)
name = try container.decode(String.self, forKey: .name)
street = try container.decode(String.self, forKey: .street)
city = try container.decode(String.self, forKey: .city)
postcode = try container.decode(String.self, forKey: .postcode)
}
the same question goes to the method in the same class,
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(type, forKey: .type)
try container.encode(quantity, forKey: .quantity)
try container.encode(extraFrosting, forKey: .extraFrosting)
try container.encode(addSprinkles, forKey: .addSprinkles)
try container.encode(name, forKey: .name)
try container.encode(street, forKey: .street)
try container.encode(city, forKey: .city)
try container.encode(postcode, forKey: .postcode)
}
I looked into all the codes, none of the 2 external parameter names were used in any parts of the code. In my knowledge, we are allowed to set the function parameter name to whatever we want.
but I think I may know the answer to the latter.
I checked the apple documentation and there is a function:
func encode(to encoder: Encoder) throws
I am wondering if this is what the class method for encoding is conforming to, hence the external parameter name has to be 'to'?
But I am still confused on the initialiser decoding part. I can't find an exact method match for the decoding function in apple documentation and the external parameter name has to be 'from' for it to work.