1

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.

Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124
  • `Any` can represent an instance of any type at all, including function types and optional types & `AnyObject` can represent an instance of any class type. So, in your case `String` Object is `Class` Object thats way its not giving warning. – Rocky Feb 06 '18 at 08:14
  • @Rocky I have updated the question. – Chen Li Yong Feb 06 '18 at 08:24
  • An optional dictionary value is nonsense. According to the dictionary definition `nil` is returned if the key does not exist. So if you want a `nil` value omit the key. And remove the trailing semicolons. They are pointless in Swift. – vadian Feb 06 '18 at 08:42
  • @vadian optional dictionary value is indeed nonsense. The problem is those optionals come from parameters. By using typecast to `as [String: AnyObject]`, any nil value is automatically not included in the final dictionary. And yes semicolons are pointless. But I switch back and forth between Obj C and Swift project, and rather than I kept getting frustrated because I forgot to put semicolons when working with Obj C, I prefer to put extra semicolons in Swift, just so that I do not lose my reflex to add semicolons after statement. – Chen Li Yong Feb 06 '18 at 08:57

1 Answers1

0

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];
Mika
  • 1,256
  • 13
  • 18
  • But that means I need to add `as Any` to every value. I was just found a workaround though, that is by cast it to `[String: AnyObject]` and then cast it to `[String: Any]`. Why is this possible? – Chen Li Yong Feb 06 '18 at 08:51
  • `Any` can by anything, `AnyObject` some object of a class, but for example it cannot be function type. You can use `Any` instea of `AnyObject`, `String`, etc.so your type casting is valid. And you are probably working with normal objects so using `AnyObject` is a good solution. – Mika Feb 06 '18 at 11:10