type casting Swift 编程语言指南的一部分说,当我们知道项目是某种类型时,可以在 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]] {
关于ios - 如何向下转换为 [String : String] in a for in loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28198620/