for循环中的Swift语法'case let'令人困惑

时间:2016-09-18 12:20:21

标签: ios swift syntax

如果目标是让'result'代表'results'数组中的一个对象,那么为什么不将case let放在下面,而只是'for result in'?我不明白为什么这里需要case let

if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    for case let result in json["results"] {
        if let restaurant = Restaurant(json: result) {
            restaurants.append(restaurant)
        }
    }
}

JSON

{
    "query": "sandwich",
    "results_count": 12,
    "page": 1,
    "results": [
        {
            "name": "Caffè Macs",
            "coordinates": {
                "lat": 37.330576,
                "lng": -122.029739
            },
            "meals": ["breakfast", "lunch", "dinner"]
        },
        ...
    ]
}

参考:https://developer.apple.com/swift/blog/

1 个答案:

答案 0 :(得分:10)

在您的情况下,不需要将case let与for循环一起使用,因为您希望results响应的所有对象,如果您想了解case let的使用方法,请检查此项。

let albumDic = [
    ("Red", 2014),
    ("1989", 2014),
    ("Fearless", 2008),
    ("Speak Now", 2008)
]

for case let (album, 2014) in albumDic {
    print("Album \(album) was released in 2014")
}

<强>输出

Album Red was released in 2014
Album 1989 was released in 2014

注意:您可以直接使用for循环,因为您需要所有对象,因此无需使用case let。所以您需要这样写。

if let results = json["results"] as? [[String: Any]]{
    for result in results {

    }
}

有关详细信息,请查看此tutorial for for。