我目前使用此模式
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"
的最佳方法或者是否有可能做出类似这样的答案,会更好吗? Answer(Unwrapping multiple optionals in a single line)
if let v = jsonResult["valid"] as? Int, s = jsonResult["status"] as? String
where is(v, valid && s, status)
感谢任何帮助,谢谢。
答案 0 :(得分:1)
你应该试试看守声明 像这样的东西
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)")
答案 1 :(得分:1)
尝试:
if let v = jsonResult["valid"] as? Int, s = jsonResult["status"] as? String where (v == valid && s == status) {}
答案 2 :(得分:1)
如果您在v
的正文中不需要s
和if
,则可以直接进行比较:
if jsonResult["valid"] as? Int == 1 && jsonResult["status"] as? String == "ok" {
// Do something
}