swift2 - Guard when setting multiple class properties in Swift 2 -
it's trivial enough this:
class collection { init(json: [string: anyobject]){ guard let id = json["id"] as? int, name = json["name"] as? string else { print("oh noes, bad json!") return } } } in case using let initialize local variables. however, modifying use class properties causes fail:
class collection { let id: int let name: string init(json: [string: anyobject]){ guard id = json["id"] as? int, name = json["name"] as? string else { print("oh noes, bad json!") return } } } it complains let or var needs used isn't case. what's proper way in swift 2?
in if let, unwrapping values optional new local variables. can’t unwrap into existing variables. instead, have unwrap, assign i.e.
class collection { let id: int let name: string init?(json: [string: anyobject]){ // alternate type pattern matching syntax might try guard case let (id int, name string) = (json["id"],json["name"]) else { print("oh noes, bad json!") self.id = 0 // must assign values self.name = "" // before returning nil return nil } // now, assign unwrapped values self self.id = id self.name = name } } this not specific class properties - can’t conditionally bind into variable, example doesn’t work:
var = 0 let s = "1" if = int(s) { // nope } instead need do:
if let j = int(s) { = j } (though of course, in case you’d better let = int(s) ?? 0)
Comments
Post a Comment