2017-06-21 125 views
-5

我有一个这样的数据结构,在swift3中嵌套数组?

var Data = [ 
      "Action" : [ 
          [ 
          "title":"The Dark Knight", 
          "thumb":"url_of_thumb" 
          ], 
          [ 
          "title": "The Godfather", 
          "Thumb":"url_of_thumb"] 
          ], 
      "Drama": [ 
          [ 
          "title": "Malgudi Days", 
          "Thumb":"url_of_thumb" 
          ] 
        ] 
      ] 

如何保存这Swift 3

+0

你可以请什么你想实现你的意思是**如何保存在swift3?**,你想要保存的位置?,你想保存在文本文件,json文件等 –

回答

0

这里是你的问题的解决方案,使用Eric Aya的代码this answer

商店中的在甲酸盐的任何阵列数据[字符串:任何]

import UIKit 

var testData = ["Action" : [["title":"The Dark Knight", "thumb":"url_of_thumb"],["title": "The Godfather", "Thumb":"url_of_thumb"]], "Drama": [["title": "Malgudi Days", "Thumb":"url_of_thumb"]]] 
var myJsonData:[String:Any] 
do { 
    let jsonData = try JSONSerialization.data(withJSONObject: testData, options: .prettyPrinted) 
    // here "jsonData" is the dictionary encoded in JSON data 

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) 
    // here "decoded" is of type `Any`, decoded from JSON data 

    // you can now cast it with the right type 
    if let JSON = decoded as? [String:Any] 
    { 
     myJsonData = JSON 
     print(myJsonData["Action"]!) 

    } 
} catch { 
    print(error.localizedDescription) 
} 

/* OUTPUT */

( { 拇指= “url_of_thumb”; 标题=“所黑暗骑士“; },{ 拇指 = ”url_of_thumb“; 标题= ”教父“; })

如果您的数据格式为[String:String],那么您也可以使用Eric Aya在此答案中给出的答案。 Convert Dictionary to JSON in Swift

+0

注意使用'Data'(这是Swift 3中的一个类型)作为变量名是一个糟糕的主意,除了事实上它是用Swift惯例命名变量并以小写字母开头。 –

+0

@LeoDabus感谢您的建议我编辑了我的答案 –

0

其实这是一个包含字典数组的字典。

可以

附注保存为属性列表:Data是斯威夫特3.一个结构,可以避免这种术语的冲突符合命名约定变量名称以小写字母开头。