检查Swift中的任何对象值

时间:2015-04-15 08:26:57

标签: swift

使用以下代码:

let decoded = NSJSONSerialization.JSONObjectWithData(data as! NSData, options: NSJSONReadingOptions.MutableContainers, error:  nil) as! [String:AnyObject]

我得到[latitude: 40.3654922, won: 1, longitude: 49.9384457, winnerID: 552e]

现在我想检查赢得的对象是否等于' 1'做一点事。但我无法检查对象的值。我有办法做到吗?

2 个答案:

答案 0 :(得分:4)

使用swift 1.2,您可以:

if let won = decoded["won"] as? Int where won == 1 {
    // do something
}

看看swift 1.2发行说明(包含在Xcode 6.3发行说明中),我们发现if let现在支持多个条件检查。例如:

if let a = foo(), b = bar() where a < b,
   let c = baz() {
}

if someValue > 42 && someOtherThing < 19, let a = getOptionalThing() where a > someValue {
}

非常强大!

答案 1 :(得分:3)

if let won = decoded["won"] as? Int {
    if won == 1 {
        // do something
    }
}