在单行上展开并检查多个可选项

  • 本文关键字:可选项 单行 ios swift
  • 更新时间 :
  • 英文 :


我现在使用这个模式

do {
    if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
        let valid: Int? = 1
        let status: String? = "ok"
            if let v = jsonResult["valid"] as? Int, s = jsonResult["status"] as? String {
                if v == valid && s == status{
                //Do something
                }
            }
    }

这是检验v == 1和s == "ok"的最佳方法吗

或者有可能做一些像这样的答案,它会更好吗?答案(在一行中展开多个可选项)

if let v = jsonResult["valid"] as? Int, s = jsonResult["status"] as? String 
   where is(v, valid && s, status)

如果您不需要vsif的主体内,您可以直接进行比较:

if jsonResult["valid"] as? Int == 1 && jsonResult["status"] as? String == "ok" {
    // Do something
}

尝试:

if let v = jsonResult["valid"] as? Int, s = jsonResult["status"] as? String where (v == valid && s == status) {}

你应该试试guard语句像这样

let dict = NSDictionary()
dict.setValue(Int(1), forKey: "one")
dict.setValue("String", forKey: "two")
guard let one = dict["one"] as? Int, two = dict["two"] as? String where one == 1 && two == "String" else  {
    print ("no")
    return
}
print ("one is (one) two is (two)")

最新更新