【问题标题】:Create Dictionary from Array in Swift 5在 Swift 5 中从数组创建字典
【发布时间】:2019-09-10 06:40:21
【问题描述】:

我需要为数组的第一个索引从具有自定义类型的数组创建一个字典。

示例数组:["ABC","ZYZ","123"]

必填结果:[{"name" : "ABC", "type:"A"},{"name" : "ZYZ", "type:"B"},{"name" : "123", "类型:"B"}]

注意第一个索引的类型 A。

我的代码

for url in urlArray {
        urlDict["name"] = url
    }

【问题讨论】:

  • 这里的逻辑是什么?为什么第一个字典是type:A 而其他字典是type:B
  • 数组的第一个索引需要单独发送到服务器。
  • 所以它总是是第一个索引?数组的内容是什么都无所谓吧?

标签: ios arrays swift dictionary


【解决方案1】:

你可以做一个map,然后单独更改第一个字典的类型:

var dicts = urlArray.map { ["name": $0, "type": "B"] }
dicts[0]["type"] = "A"

查看所有字典键是如何相同的,并且您将其发送到服务器,Codable 结构可能是更好的选择。

struct NameThisProperly : Codable {
    var name: String
    var type: String
}

var result = urlArray.map { NameThisProperly(name: $0, type: "B") }
result[0].type = "A"
do {
    let data = try JSONDecoder().encode(result)
    // you can now send this data to server
} catch let error {
    ...
}

【讨论】:

    【解决方案2】:

    我想你可以使用高阶函数,例如mapreduce

    这是一个使用reduce的示例

    var array = ["ABC","ZYZ","123"]
    
    var result = array.reduce([[String: String]](), { (previous, current) -> [[String: String]] in
        let type = previous.count == 0 ? "A" : "B"
        let dictForCurrent = [
            "name": current,
            "type": type
        ]
        return previous + [dictForCurrent]
    })
    
    print(result)
    

    结果:

    [[“类型”:“A”,“名称”:“ABC”],[“类型”:“B”,“名称”:“ZYZ”],[“名称”: "123", "type": "B"]]

    【讨论】:

      【解决方案3】:

      使用reduce 将数组转换为字典:

      let resultDict: [String: String]
            = array.reduce(into: [:]) { dict, url in
              dict["name"] = url
            }
      

      结果将如下所示:

      [
        "name": URL1,
        "name": URL2
      ]
      

      【讨论】:

      • 在 Stack Overflow 上不鼓励仅使用代码的答案,因为它们没有解释它如何解决问题。请编辑您的答案以解释此代码的作用以及它如何回答问题,以便它对 OP 以及其他有类似问题的用户有用。
      【解决方案4】:

      使用 map(_:)array 的每个元素转换为dictionary 就像这样,

      let arr = ["ABC","ZYZ","123"]
      let result = arr.map { (element) -> [String:String] in
          var dict = [String:String]()
          dict["name"] = element
          if let char = element.first {
              dict["type"] = String(char)
          }
          return dict
      }
      
      print(result)
      

      【讨论】:

        【解决方案5】:

        由于您关心索引,我的方法将使用enumerated() 给出索引

        
           let array = ["ABC","ZYZ","123"]
           var results: [[String: String]] = []
           for (i, content) in array.enumerated() {
              let type: String = i == 0 ? "A" : "B"
              results.append(["name": content, "type": type])
            }
            print(result)
        
        // [["type": "A", "name": "ABC"], ["name": "ZYZ", "type": "B"], ["type": "B", "name": "123"]]
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-01-05
          • 1970-01-01
          • 1970-01-01
          • 2016-03-18
          • 1970-01-01
          • 1970-01-01
          • 2018-01-30
          • 2021-01-17
          相关资源
          最近更新 更多