How to convert a [String: Any] to [String: String] in Swift. I've tried to cast like this, but it didn't help:
for (key, value) in dictionary {
dictionary[key] = value as! String
}
How to convert a [String: Any] to [String: String] in Swift. I've tried to cast like this, but it didn't help:
for (key, value) in dictionary {
dictionary[key] = value as! String
}
Update: If you need to include the non-string values too as #user has asked in the comments you could use the following approach:
let anyDict = ["String0": "0", "String1": 1] as [String : Any]
let stringDict = anyDict.compactMapValues { "\($0)" }
(Old)Here:
import Foundation
let anyDict = ["String0": "0", "String1": 1] as [String : Any]
var stringDict = [String: String]()
for (key, value) in anyDict {
if let value = value as? String {
stringDict[key] = value
}
}
print(stringDict)
If literally all you want to do is:
Convert [String: Any] to [String: String] in Swift.
And if you're happy to get nothing back if any of the Anys are not Strings, then you can do:
Safe:
if let stringDictionary = dictionary as? [String: String] {
//Use your new stringDictionary here
}
Unsafe:
let stringDictionary = dictionary as! [String: String]