在Swift 2中设置多个类属性时进行防护 [英] Guard when setting multiple class properties in Swift 2

查看:132
本文介绍了在Swift 2中设置多个类属性时进行防护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做这样的事情很简单:

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

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

In that case we were using let to initialize local variables. However, modifying it to use class properties causes it to 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
        }
    }

}

它抱怨需要使用letvar,但是显然不是这样.在Swift 2中执行此操作的正确方法是什么?

It complains that let or var needs to be used but obviously that isn't the case. What's the proper way to do this in Swift 2?

推荐答案

if let中,您正在将可选值中的值作为新的局部变量展开.您无法将展开为现有变量.相反,您必须先解开包装,然后进行分配

In the if let, you are unwrapping values from the optional as new local variables. You can’t unwrap into existing variables. Instead, you have to unwrap, then assign i.e.

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 is not specific to class properties - you can’t conditionally bind into any variable, for example this doesn’t work:

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

}

相反,您需要这样做:

if let j = Int(s) {
  i = j
}

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

(though of course, in this case you’d be better with let i = Int(s) ?? 0)

这篇关于在Swift 2中设置多个类属性时进行防护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆