Reputation: 2896
Convert [String:Any] dictionary array to [String:String] in Swift
I have an array of dictionary <String,Any>
type. Now I want to convert to string because I want to show data in textField
and text field not understand Any
data type.
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]]()
Upvotes: 3
Views: 13201
Reputation: 318904
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"]]
Upvotes: 5
Reputation: 114
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)
}
Upvotes: 1
Reputation: 285
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
}
Upvotes: 7