[swift-users] Why this string not work. Any and Optionals in dictionary
Ole Begemann
ole at oleb.net
Mon Jan 23 05:13:26 CST 2017
> I have a simple expression with Any and is not work. Why?
>
> vardictarray: [[String: Any]] = [["kek": nil]]
>
> \\ Nil is not compatible with expected dictionary value type 'Any'
`nil` is just a literal value that doesn't have a specific type. Even
though you want to put it in a dictionary whose `Value` type is `Any`,
you must first tell the compiler what type your `nil` value is: for
example, is it an Optional<Int> or an Optional<String>? Or any other
type that conforms to `ExpressibleByNilLiteral`, for that matter — `nil`
is not confined to `Optional`.
This works:
var dictarray: [[String: Any]] = [["kek": nil as Int?]]
This compiles but the compiler raises a warning: "Expression implicitly
coerced from 'Int?' to Any". To silence the warning you'd need to add
another cast:
var dictarray: [[String: Any]] = [["kek": nil as Int? as Any]]
More information about the swift-users
mailing list