I'm currently learning the type "Any" in swift and have come up with the following code
let optionalDouble: Double? = 45.1
let things: [Any] = [
0,
0.0,
1.1,
optionalDouble, //expression implicitly coerced from Double? to Any
-4.0,
("hello", 1),
Movie(name: "Titanic", director: "James"),
{(name: String) -> String in
return "hello \(name)"
},
{},
["one": 1, "two": 2]
]
However, when I tried to add an optional Double
value to the [Any]
array, swift compiler displayed an warning saying
//expression implicitly coerced from Double? to Any
I thought type Any
can represent everything and an array of type [Any]
can contain everything. So why the warning message?
It's only a warning. The compiler wants to make sure you know you're doing an odd thing, wrapping an Optional inside an Any.
In the line that's giving trouble, write optionalDouble as Any
to suppress the warning.