Nbody Nbody Nbody Nbody - 1 year ago 75
Swift Question

"Implicit Any? to Any cast" warning when passing Any? type variable in as Any? type parameter

The warning

Expression implicitly coerced from 'Any?' to Any
is raised when passing an
Any?
type value in as an
Any?
type parameter but I don't see where casting is happening. It also seems to only happen with dictionary values. The example below shows when it happens:

func someFunc(_ aParam : Any?) {}

let testDict : Dictionary<String, Any?> = ["Test": "Hello"];
someFunc(testDict["Test"]);


If the function is called with a normal
Any?
value, there is no warning, like so:

let test : Any? = nil;
someFunc(test);

Answer Source

Dictionary look ups return optional values because the key might not exist. In the case of a non-existent key, the look up returns nil, so the type of the dictionary look up has to be optional.

In your case, your values are of type Any?, so a look up from that dictionary returns a doubly wrapped optional Any??. So you are trying to pass a value of type Any?? to a function that takes Any?.

If you use optional binding to handle and unwrap the dictionary access, everything works:

let testDict : Dictionary<String, Any?> = ["Test": "Hello"];
if let value = testDict["Test"] {
    // "Test" key is valid
    someFunc(value);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download