I want to convert a [String: Anyobject] dictionary to [String: String] dictionary?
How can I do this?
2 Answers
You cannot convert a dictionary directly from [String: AnyObject] to [String: String]: since AnyObject can hold different types of values in the same dict, each such value entry isn't necessarily convertable to String.
Instead, you need to go over each key-value pair and conditionally perform a value conversion to String, if possible. E.g.:
// (example) source dict
let dict: [String: AnyObject] = ["foo": "1" as AnyObject,
"bar": 2 as AnyObject,
"baz": "3" as AnyObject]
// target dict
var targetDict = [String: String]()
for (key, value) in dict {
if let value = value as? String { targetDict[key] = value }
} // targetDict: ["foo": "1", "baz": "3"]
Comments
Simply, you can do it this way:
if let castedDict = dictionary as? [String: String] {
print("Converted successfully: \(castedDict)")
} else {
print("Failed to cast the dictionary")
}
3 Comments
LoveCode
Thank you, but castedDict was nil.
Mo Abdul-Hameed
This casting will fail if the dictionary you're trying to cast can not be cast to
[String: String]. I updated my code to make that more clear.LoveCode
Thank you for your kind help.