LoveCode
LoveCode

Reputation: 69

Swift 3: How to convert from [String: AnyObject] to [String: String]?

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

Upvotes: 0

Views: 2917

Answers (2)

dfrib
dfrib

Reputation: 73176

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"]

Upvotes: 2

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

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")
}

Upvotes: 1

Related Questions