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

3 syntax ios swift

如果目标是让'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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

JSON

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

REF:https://developer.apple.com/swift/blog/

Nir*_*v D 10

在你的情况下,不需要使用case letfor循环,因为你想要所有的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")
}
Run Code Online (Sandbox Code Playgroud)

产量

Album Red was released in 2014
Album 1989 was released in 2014
Run Code Online (Sandbox Code Playgroud)

注意:您可以直接使用in循环,case let因为您需要所有对象,因此您需要像这样编写.

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

    }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看本教程.