【问题标题】:Storing Dictionary in single Array [closed]将字典存储在单个数组中[关闭]
【发布时间】:2018-10-11 09:22:30
【问题描述】:

我得到 "files" 的 json 作为响应,我想将它们存储在单个 Array 中。由于我是 swift 开发的新手,我无法弄清楚如何做到这一点。任何帮助将不胜感激。我想要它们如下

let myFileArray = [file1, file2.....]

【问题讨论】:

  • "doc":[{"nameChange":[{"file_type":"jpg","file":"file.jpg"},{"file_type":"jpg","file ":"file2.jpg"}.......这是我的回应
  • 您应该创建适当的对象并将它们存储到数组中,尝试使用 Swift 4 中的 Codable
  • @RishabhShukla 你的问题不清楚。 Array 全部 files 或全部 filesTypes 或其他什么你想要什么?

标签: swift xcode


【解决方案1】:

示例:-responce 是您的网络服务数据

 let data = responce as? [String:AnyObject]
 let respArr = data["doc"] as? [AnyObject]
 let responceData = respArr.first as? [String:AnyObject]
 let nameChange = responceData["nameChange"] as? as! Array<Dictionary<String, Any>>
 let strFileName = nameChange["file"] as? String
 Print("\(nameChange.count),\(strFileName)")

【讨论】:

    【解决方案2】:

    您可以使用flatMapcompactMap 来执行此操作:

    如果您使用的是 swift 4.1,请使用 compactMap,否则请使用 flatMap

    // Your dictionary
    let dictionary = response as? [String: Any]
    // Create an empty Array
    var myFileArray = [String]()
    // Get the doc array
    if let docs = dictionary?["doc"] as? [[String: Any]] {
        // for each doc array
        for doc in docs {
            // get the nameChange array
            if let nameChange = doc["nameChange"] as? [[String: Any]] {
                // convert the inner dictionary to string array
                let fileNameArray = nameChange.compactMap { (dictionary) -> String? in
                    return dictionary["file"] as? String
                }
    
                // append the array into main array
                myFileArray.append(contentsOf: fileNameArray)
            }
        }
    }
    // Here is your final string array of filename
    print(myFileArray)
    

    【讨论】:

    • 非常感谢 ..!
    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2021-08-16
    • 2012-09-14
    • 1970-01-01
    相关资源
    最近更新 更多