user3051755 user3051755 - 1 month ago 20
Swift Question

Loop through [[String: Any]]

With

let posts = json["posts"] as? [[String: Any]] ?? []
print(posts)


I get

[["id": 1, "title": title 1], ["id": 2, "title": title 2], ["id": 3, "title": title 3], ["id": 4, "title": title 4], ["id": 5, "title": title 5]]


How can I loop through this to get value of each
id
and
title
?

Answer

Iterate through posts with a for-loop and make sure you have a value with guard.

for post in posts{
    guard let id = post["id"] as? Int,
          let title = post["title"] as? String else { continue }
}