2
class User {
    var id: Int!
    init(data: JSON){
        id = data["id"].int
        //if id doesn't exist, then cancel the init and return nil.
    }
}

I want to initialize a user by passing a JSON to its constructor. However, sometimes the JSON doesn't match. In this case, I want the initialization to be cancelled, and User to be nil.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

4

something like this:

class User {
    var id: Int!
    init?(data: JSON) {
        guard let id = Int(data["id"]) else {
            return nil
        }

        self.id = id
    }
}
André Slotta
  • 13,774
  • 2
  • 22
  • 34
1

Create a "Failable Initializer" - that is one will either return self or nil.

class User {
  var id: Int!

  init?(data: JSON){
    if <id doesn't exist> {
      return nil
    }

    id = data["id"].int
  }
}
Blake Lockley
  • 2,931
  • 1
  • 17
  • 30