Codable with init(with decode:)

How can I convert a String type (numChildren) into an Int via init(with coder). Please look at the sample struct below

struct Person: Codable { let firstName: String let lastName: String var numChildren: String

init(with coder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let firstName = try container.decode(String.self, .firstName) let lastName = ... let numChildren = try container.decode(String.self, .numChildren

(what should be done after the above line? Thanks for your help.)

}

private enum CodingKeys: String, CodingKey { case firstName = "first_Name" case lastName = "last_Name" case numChildren

}

Answered by Engineer in 678354022

You could declare numChildren like this: var numChildren: Int?

and then in your initializer you could have something like:

init(with coder: Decoder) throws {
   let numChildrenString = try container.decode(String.self, .numChildren)
   self.numChildren = Int(numChildrenString)
}
Accepted Answer

You could declare numChildren like this: var numChildren: Int?

and then in your initializer you could have something like:

init(with coder: Decoder) throws {
   let numChildrenString = try container.decode(String.self, .numChildren)
   self.numChildren = Int(numChildrenString)
}
Codable with init(with decode:)
 
 
Q