0

I want to convert a [String: Anyobject] dictionary to [String: String] dictionary? How can I do this?

2 Answers 2

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Thank you, but castedDict was nil.
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.
Thank you for your kind help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.