In if let you expand the values ββfrom optional as new local variables. You cannot expand existing variables. Instead you need to unzip, then assign ie
class Collection { let id: Int let name: String init?(json: [String: AnyObject]){ // alternate type pattern matching syntax you might like to try guard case let (id as Int, name as String) = (json["id"],json["name"]) else { print("Oh noes, bad JSON!") self.id = 0 // must assign to all values self.name = "" // before returning nil return nil } // now, assign those unwrapped values to self self.id = id self.name = name } }
This does not apply to class properties - you cannot conditionally bind to any variable, for example, this does not work:
var i = 0 let s = "1" if i = Int(s) {
Instead, you need to do:
if let j = Int(s) { i = j }
(although, of course, in this case you are better off with let i = Int(s) ?? 0 )
source share