2017-06-21 135 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.一個結構,可以避免這種術語的衝突符合命名約定變量名稱以小寫字母開頭。