Search code examples
swiftoption-typeanyanyobject

Why if I typecast String? to Any, Xcode gives off warning, but not with AnyObject?


This code gives warning "Expression implicitly coerced from 'String?' to Any."

let email : String?;
let password : String?;
let dict = ["email": email, "password": password] as [String: Any];

But this code does not.

let email : String?;
let password : String?;
let dict = ["email": email, "password": password] as [String: AnyObject];

Why? And how can I make that Any does not bother me with warning about optionals like AnyObject?

EDIT:

This code also does not gives away warning:

let email : String;
let password : String;
let dict = ["email": email, "password": password] as [String: Any];

But I need to be able to incorporate both object and optionality in this case. It seems the warning only appears if the variable type is both object and optional.


Solution

  • According to Swift Language Guide you are expected to get a warning when casting optional to Any (see note at the bottom of the page). You can get rid of warning by casting optional value to Any as shown below.

    let email : String?;
    let password : String?;
    let dict = ["email": email as Any, "password": password as Any] as [String: Any];