[英]Create Dictionary from Array in Swift 5
我需要為數組的第一個索引創建一個自定義類型的數組字典。
樣本數組:["ABC","ZYZ","123"]
所需結果:[{"name" : "ABC", "type:"A"},{"name" : "ZYZ", "type:"B"},{"name" : "123", "type: “乙”}]
注意第一個索引的類型 A。
我的代碼
for url in urlArray {
urlDict["name"] = url
}
我想您可以使用高階函數,例如map
或reduce
這是一個使用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)
結果:
[["type": "A", "name": "ABC"], ["type": "B", "name": "ZYZ"], ["name": "123", "type": “乙”]]
您可以做一個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 {
...
}
使用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)
使用reduce
將數組轉換為字典:
let resultDict: [String: String]
= array.reduce(into: [:]) { dict, url in
dict["name"] = url
}
結果將如下所示:
[
"name": URL1,
"name": URL2
]
由於您擔心索引,我的方法將使用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"]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.