将[String:Any]字典数组转换为Swift中的[String:String]
我有一个字典<String,Any>
类型的数组。现在我想转换为字符串,因为我想在textField
中显示数据,而文本字段则不了解Any
数据类型。
我的数据如下:
var myarr = [[String:Any]]()
[
[
"Area" : "",
"Good" : "-",
"Level" : 2,
"Link" : "<null>",
"Photo" : "-",
"Repair" : "-",
"Section" : "Others"
],
[
"Area" : "",
"Good" : "N",
"Level" : 2,
"Link" : "http://google.com",
"Photo" : 1,
"Repair" : "Y",
"Section" : "Grounds"
]
]
我想要新的Array Dictionary:
var myarr = [[String:String]]()
答案 0 :(得分:5)
地图是你的朋友,也许就像
let stringDictionaries: [[String: String]] = myarr.map { dictionary in
var dict: [String: String] = [:]
dictionary.forEach { (key, value) in dict[key] = "\(value)" }
return dict
}
答案 1 :(得分:4)
这是一个实际给出正确结果的解决方案:
let myarr = [
[
"Area" : "",
"Good" : "-",
"Level" : 2,
"Link" : "<null>",
"Photo" : "-",
"Repair" : "-",
"Section" : "Others"
],
[
"Area" : "",
"Good" : "N",
"Level" : 2,
"Link" : "http://someurl",
"Photo" : 1,
"Repair" : "Y",
"Section" : "Grounds"
]
]
var newarr = [[String:String]]()
for dict in myarr {
var newdict = [String:String]()
for (key, value) in dict {
newdict[key] = "\(value)"
}
newarr.append(newdict)
}
print(newarr)
输出:
[[“Level”:“2”,“Area”:“”,“Good”:“ - ”,“Link”:“&lt; null&gt;”,“修复”:“ - ”,“照片” :“ - ”,“Section”:“Others”],[“Level”:“2”,“Area”:“”,“Good”:“N”,“Link”:“http://someurl”, “修复”:“Y”,“照片”:“1”,“部分”:“理由”]]
答案 2 :(得分:1)
您可以使用以下代码创建新词典:
var newArray:[[String: String]] = []
for data in myarr {
var dict: [String: String] = [:]
for (key, value) in data {
let strData = String(describing: value)
dict[key] = strData
}
newArray.append(dict)
}