-2

I would like to parse json file in init of my model. I want it to take URL and initialize all stored properties. Like:

init(from url: URL) { ... },

so the question is how do I do it? I tried to do it this way:

let info = try JSONDecoder().decode(Model.self, from: data),

but it just creates a new object and seems like a bad decision.

Thanks.

Egor Kolyshkin
  • 117
  • 1
  • 10

1 Answers1

0

I created a codable struct with the kind of init you want :

struct NameObject: Codable {
    let id: Int
    let name: String
    enum CodingKeys: String, CodingKey {
        case id
        case name
    }

    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }

    init(withData data: Data) {
        do {
            self = try JSONDecoder().decode(NameObject.self, from: data)
        } catch {
            self.id = 0
            self.name = "unknown"
            // error
        }
    }
}
Damien
  • 3,322
  • 3
  • 19
  • 29
  • Remove the do try catch and make your init throw. Creating an useless object doesn’t make any sense – Leo Dabus Oct 19 '17 at 14:59
  • Btw why would you catch the error if you won’t use it. Better to make a fallible initializer – Leo Dabus Oct 19 '17 at 15:17
  • I wasn't thinking how to write the best init possible, just how to solve OP problem. BTW you can edit my answer if you want ;) – Damien Oct 20 '17 at 09:31