且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift 3中从字典中获取数组

更新时间:2022-12-05 17:17:15

根据JSON,将打印aarti数组中的所有值:

According to the JSON this prints all values in the aarti array:

if let JSON = response.result.value as? [String:Any] {   
   if let response = JSON["wsResponse"] as? [String:Any],
      let aarti = response["aarti"] as? [[String:Any]] {

         for item in aarti {
            let content = item["content"] as! String
            let identifier = item["identifier"] as! String
            let title = item["title"] as! Int
            let type = item["type"] as! String
            print(content, identifier, title, type)
        }
   }
}

在Swift中基本上不使用NSDictionary / NSArray.

Basically do not use NSDictionary / NSArray in Swift.

如果要将所有content值放入数组中,请使用flatMap.该行可以代替整个重复循环.

If you want to put all content values in an array use flatMap. The line can replace the whole repeat loop.

 let contentArray = aarti.flatMap { $0["content"] as? String }

PS:如果要根据值创建多个数组,请不要这样做:使用自定义结构或类

PS: If you are going to create multiple arrays from the values don't do that: Use a custom struct or class