4

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
}
2
  • 1
    Could you explain your use case? Commented May 16, 2020 at 11:07
  • Why didn't it help? Can you explain what kind of data you have to start with, are all values of type String or can it be mixed and if so what to do with the non String values. Commented May 16, 2020 at 12:56

3 Answers 3

13

Here is safe approach, the converted will contain only [String: String], non-string Any will be dropped:

let converted = dictionary.compactMapValues { $0 as? String }
Sign up to request clarification or add additional context in comments.

Comments

1

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)

3 Comments

This does not work for me. Everything that is not a string in the dictionary (i.e. a Bool for example or Int), is skipped and not added to the dictionary as a String.
@SouthernYankee65 check the update.
Thanks for the update. This works as is. I now need to find a way to handle a nested dictionary... [String:[String:[UInt32]]]
0

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]

Comments

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.