Tuesday, February 27, 2018

Decoding Dictionaries in Swift

Sam Deane:

Swift’s Codable support is really great for doing this when you’ve got JSON or a Plist, but not all dictionary data ultimately lives in a file.

For example, I was recently doing some stuff with the Disk Arbitration framework. This has a DADiskCopyDescription call which gives you back a dictionary of known keys (many of which may be missing). This dictionary only ever exists in memory.

What I really want to do in this situation is extract some of these keys into a structure or object as a way of validating that I have what I need, and discarding anything I don’t need.


The Codable support would be ideal here, except that as it comes out-of-the-box, it appears that I’d have to convert the dictionary into JSON first in order to convert it back. This seems… non optimal… so I set out to make encoder / decoder classes which just work with dictionaries.

Comments RSS · Twitter

Leave a Comment