[swift-users] Why this string not work. Any and Optionals in dictionary
Quinn "The Eskimo!"
eskimo1 at apple.com
Mon Jan 23 05:10:31 CST 2017
On 23 Jan 2017, at 10:24, Седых Александр via swift-users <swift-users at swift.org> wrote:
> I have a simple expression with Any and is not work. Why?
The problem here is that:
* `nil` is syntactic sugar for `Optional<Wrapped>.none`, where `Optional` is generic on the `Wrapped` type
* You’re not given the compiler any information about `Wrapped`
You could fix this by writing:
var dictarray: [[String: Any]] = [["kek": Optional<Int>.none]]
replacing `Int` with whatever type you’d expect values of `kek` key to be.
Note: This generates a warning because the conversion from a `Optional` to `Any` is a common pitfall.
However, it’s probably better to rethink your overall approach. In most cases arrays of dictionaries of any type are a poor choice in Swift. In my experience most folks encounter problems like this because they’ve read some general data structure (JSON, property list, or whatever) and are working with the low-level import format. IMO it’s better to sort out this problem when you bring the data into Swift. That is:
1. On import, convert `[String:Any]` to some defined-in-Swift model value (class or struct)
2. Write Swift code that works with that model value
3. On export, convert the model value back to the external representation
Share and Enjoy
--
Quinn "The Eskimo!" <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
More information about the swift-users
mailing list