'Convert [String: Any] to [String: String] in swift
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
}
Solution 1:[1]
Here is safe approach, the converted will contain only [String: String], non-string Any will be dropped:
let converted = dictionary.compactMapValues { $0 as? String }
Solution 2:[2]
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)
Solution 3:[3]
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 Any
s are not String
s, then you can do:
Safe:
if let stringDictionary = dictionary as? [String: String] {
//Use your new stringDictionary here
}
Unsafe:
let stringDictionary = dictionary as! [String: String]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Asperi |
Solution 2 | |
Solution 3 | janakmshah |