在Swift 2中设置多个类属性时保护

Luk*_*pan 5 swift swift2 guard-statement

做这样的事情是微不足道的:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在那种情况下,我们let用来初始化局部变量.但是,将其修改为使用类属性会导致它失败:

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
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

它抱怨letvar需要使用,但显然情况并非如此.在Swift 2中执行此操作的正确方法是什么?

Air*_*ity 12

在中if let,您将可选的值作为新的局部变量展开.你不能解开现有变量.相反,你必须打开,然后分配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
    }

}
Run Code Online (Sandbox Code Playgroud)

这不是特定于类属性 - 您不能有条件地绑定任何变量,例如这不起作用:

var i = 0
let s = "1"
if i = Int(s) {  // nope

}
Run Code Online (Sandbox Code Playgroud)

相反,你需要做:

if let j = Int(s) {
  i = j
}
Run Code Online (Sandbox Code Playgroud)

(当然,在这种情况下,你会更好let i = Int(s) ?? 0)