如何在 for in 循环中向下转换为 [String: String]?
How to downcast to [String: String] in a for in loop?
Swift 编程语言指南的 type casting 部分说,当我们知道项目是某种类型时,可以在 for in 循环中向下转换:
Because this array is known to contain only Movie instances, you can
downcast and unwrap directly to a non-optional Movie with the forced
version of the type cast operator (as):
for movie in someObjects as [Movie] {
println("Movie: '\(movie.name)', dir. \(movie.director)")
}
我正在尝试对具有以下格式的已解析 JSON 执行相同操作:
{ "data":
{"promotions": [
{ "id": "1",
"title": "Some promo",
"route": "http://www.....jpg"
} ,
{ "id": "2",
"title": "Promo 2",
"route": "http://www.....jpg"
} ]
}
}
我的代码:
if let data = json["data"] as? NSDictionary {
if let promos = data["promotions"] as? NSArray {
for i in promos as [String: String] { //<- error here
if i["id"] != nil && i["title"] != nil && i["route"] != nil {
self.promotions.append(Promotion(id: i["id"], title: i["title"], imageURL: i["route"]))
}
}
}
}
然而,这个显示错误:'String' is not identical to 'NSObject'
。 JSON 解析正确,如果我单独投射它们,我可以使用这些项目,所以这个有效:
for i in promos {
var item = i as [String: String]
if item["id"] != nil && item["title"] != nil && item["route"] != nil {
self.promotions.append(Promotion(id: item["id"]!, title: item["title"]!, imageURL: item["route"]!))
}
}
我在这里错过了什么?为什么我不能将整个数组投射到 for...in
?
在这种情况下,演员表作用于 promos
而不是 i
。由于 promos
是 [String: String]
个字典的数组,因此您需要将 promos
转换为 [[String: String]]
。当您这样做时,i
将具有 [String: String]
类型,因为它是 [[String: String]]
数组的一个元素。
for i in promos as [[String: String]] {
Swift 编程语言指南的 type casting 部分说,当我们知道项目是某种类型时,可以在 for in 循环中向下转换:
Because this array is known to contain only Movie instances, you can downcast and unwrap directly to a non-optional Movie with the forced version of the type cast operator (as):
for movie in someObjects as [Movie] {
println("Movie: '\(movie.name)', dir. \(movie.director)")
}
我正在尝试对具有以下格式的已解析 JSON 执行相同操作:
{ "data":
{"promotions": [
{ "id": "1",
"title": "Some promo",
"route": "http://www.....jpg"
} ,
{ "id": "2",
"title": "Promo 2",
"route": "http://www.....jpg"
} ]
}
}
我的代码:
if let data = json["data"] as? NSDictionary {
if let promos = data["promotions"] as? NSArray {
for i in promos as [String: String] { //<- error here
if i["id"] != nil && i["title"] != nil && i["route"] != nil {
self.promotions.append(Promotion(id: i["id"], title: i["title"], imageURL: i["route"]))
}
}
}
}
然而,这个显示错误:'String' is not identical to 'NSObject'
。 JSON 解析正确,如果我单独投射它们,我可以使用这些项目,所以这个有效:
for i in promos {
var item = i as [String: String]
if item["id"] != nil && item["title"] != nil && item["route"] != nil {
self.promotions.append(Promotion(id: item["id"]!, title: item["title"]!, imageURL: item["route"]!))
}
}
我在这里错过了什么?为什么我不能将整个数组投射到 for...in
?
在这种情况下,演员表作用于 promos
而不是 i
。由于 promos
是 [String: String]
个字典的数组,因此您需要将 promos
转换为 [[String: String]]
。当您这样做时,i
将具有 [String: String]
类型,因为它是 [[String: String]]
数组的一个元素。
for i in promos as [[String: String]] {