Casting from Any to [String: Any]

Hi guys!

Sorry if it maybe a dumb question, but I really couldn't find any clear answer to this question in mind. Imagine the following code:

let objcDict: NSDictionary = ["one": 3, "two": "twoValue", "three": "three"]
let anyDict = objcDict as Any

if let dict = anyDict as? [String: Any] {
    print("It's a dict")
} else {
    print("It's not")

So my main concern is: the casting from anyDict which is Any to [String: Any] is it a O(n) as swift needs to make sure that every key is actually a String and not just any Hashable or is there some shortcut that swift has when casting from NSDictionary to swift Dictionary?

Thanks in advance!

1 Like

It is O(n).

Note, the Any isn't changing much here. It would also be O(n) to write it this way:

let objcDict: NSDictionary = ["one": 3, "two": "twoValue", "three": "three"]
let dict = objcDict as? [String: Any]

Thanks a lot! That's exactly what I was thinking!

Maybe one follow-up question. If we do:

let someVal: Any /// set value as any
let array = someVal as? [Any]

is this also linear operation or because it's an array of Any, swift doesn't really need to cast every element and can just check in constant time if it's an array or not? Because basically any Array can be casted to [Any]