[英]Convert Any dictionary array to String in Swift
Convert [String:Any] dictionary array to [String:String] in Swift
在Swift中将[String:Any]字典数组转换为[String:String]
I have an array of dictionary <String,Any>
type. 我有一个字典
<String,Any>
类型的数组。 Now I want to convert to string because I want to show data in textField
and text field not understand Any
data type. 现在我想转换为字符串因为我想在
textField
和text字段中显示数据不理解Any
数据类型。
My data like this: 我的数据是这样的:
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"
]
]
and I want new Array Dictionary: 我想要新的数组字典:
var myarr = [[String:String]]()
Map is your friend, maybe something like 地图是你的朋友,也许就像是
let stringDictionaries: [[String: String]] = myarr.map { dictionary in
var dict: [String: String] = [:]
dictionary.forEach { (key, value) in dict[key] = "\(value)" }
return dict
}
Here is one solution that actually gives the correct results: 这是一个实际给出正确结果的解决方案:
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)
Output: 输出:
[["Level": "2", "Area": "", "Good": "-", "Link": "<null>", "Repair": "-", "Photo": "-", "Section": "Others"], ["Level": "2", "Area": "", "Good": "N", "Link": " http://someurl ", "Repair": "Y", "Photo": "1", "Section": "Grounds"]]
[[“Level”:“2”,“Area”:“”,“Good”:“ - ”,“Link”:“<null>”,“修复”:“ - ”,“照片”:“ - ” ,“Section”:“Others”],[“Level”:“2”,“Area”:“”,“Good”:“N”,“Link”:“ http:// someurl ”,“Repair”: “Y”,“Photo”:“1”,“Section”:“Grounds”]]
You can create new dictionary using following code: 您可以使用以下代码创建新词典:
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.