【问题标题】:Nested Array in swift3? [closed]swift3中的嵌套数组? [关闭]
【发布时间】:2017-11-23 19:11:02
【问题描述】:

我有这样的数据结构,

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

【问题讨论】:

  • 请问你想达到什么意思如何在swift3中保存?,你想保存在哪里?,你想如何保存在文本文件中, json 文件等

标签: ios arrays swift swift3 jsonserializer


【解决方案1】:

这是您的问题的解决方案,使用Eric Ayathis answer 中的代码。

将您的数据存储在任意的甲酸[String:Any]数组中

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)
}

/* 输出*/

( { 拇指 = "url_of_thumb"; title = "黑暗骑士"; }, { 拇指 = "url_of_thumb"; title = "教父"; })

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

【讨论】:

  • 请注意,使用Data(Swift 3 中的一种类型)作为变量名是个坏主意,因为 Swift 约定以小写字母开头的变量命名。
  • @LeoDabus 感谢您的建议我编辑了我的答案
【解决方案2】:

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

你可以保存它

旁注:Data 是 Swift 3 中的结构体。您可以通过遵循变量名称以小写字母开头的命名约定来避免这种术语冲突。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-09
    • 2020-07-19
    • 1970-01-01
    • 2018-05-15
    • 2021-07-31
    • 1970-01-01
    • 2020-02-22
    • 2022-01-09
    相关资源
    最近更新 更多