Monday, October 19, 2015 [Tweets] [Favorites]

Options Dictionaries vs. Sets of Enums

Erica Sadun:

In Swift, you can re-architect this key-based system into a simple enumeration, specifying the valid type associated with each key case. Here’s what this looks like for the five cases listed above. The associated types are pulled from the existing pixel buffer attribute key docs.

enum CVPixelBufferOptions {
 case CGImageCompatibility(Bool)
 case CGBitmapContextCompatibility(Bool)
 case ExtendedPixelsRight(Int)
 case ExtendedPixelsBottom(Int)
 case PixelFormatTypes([PixelFormatType])
 // ... etc ...
}

Re-designing options this way produces an extensible enumeration with strict value typing for each possible case. This approach offers you a major type safety victory compared to weak dictionary typing.

However, a limitation is that currently you have to use an array of options rather than a set (unless you want to make the options hashable yourself).

3 Comments

Annoter limitation: you can't specify new cases in extensions. In other word, this works well for a closed set of options; if however you are writing a framework and expects applications to add some options of their own, don't go this way.

@Michel Related: What happens if the framework wants to add options? Is that possible? Do your switch statements suddenly become non-exhaustive at runtime?

[TL;DR version of the comment I already left over there]

It's the Achilles' heel of every geek: discovering an thrillingly original and unorthodox way to perform a task for which the language has already provided a perfectly capable, established, familiar set of features. In this case, optional parameters for optionality, and structs for grouping if also required.

(Not that Swift's rampantly self-indulgent featuritis helps to define and delineate its semantics, mind.)

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment