如何在swift中迭代一个AnyObject可选的Array

时间:2015-07-23 15:13:12

标签: arrays swift loops optional

for driver: AnyObject in DataCache.drivers! {
    if (driver.id == id) {
            return driver;
    }
}

1 个答案:

答案 0 :(得分:0)

您的DataCache.drivers是json。您需要使用NSJSONSerialization解析它。见下面的代码。

let js = "{ \"id\": 123, \"name\": \"ravi\", \"currentVehicle\": { \"id\": 144241, \"vrn\": \"ML57CEU3\" }, \"email\": \"r.r@gmail.com\", \"telephone\": \"07476828399\", \"mobile\": null, \"licenseNumber\": \"123\", \"licensePoints\": 0, \"notes\": null, \"fobIds\": [] } "

if let data = js.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) 
{
    let dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as! Dictionary<String, AnyObject>

    let id = dict["id"]
    print("your id: \(id)")
}

希望有所帮助!