ios - 如何向下转换为 [String : String] in a for in loop?

标签 ios json swift casting nsdictionary

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/

相关文章:

ios - 彼此相切的圆。我如何检测哪个圆被点击了?

ios - 移动时为多个帧设置动画的正确方法

java - 使用gson解析大json文件

objective-c - AVMutableVideoComposition 有时无法播放视频

ios - 在 : 以下使用 imagePickerController 委托(delegate)函数时获取模糊引用

ios - Objective-C 中类似 Photoshop 的曲线工具

javascript - TypeScript 类到 JSON

java - 如何将 JSONObject 转换为带有字符串变量的 Java Bean?

ios - UICollectionViewCell 未选中

ios - Parse Swift - 子类化 PFObject - 设置属性导致应用程序挂起且没有错误消息