Saturday, March 19, 2016

Using ArrayLiteralConvertible to initialize swift OptionSetType objects

I was recently working on a program where I needed to configure the autoresizingMask property of a CALayer object. The autoresizingMask property is a bitmask of CAAutoresizingMask enum values. I got a little bit confused because the example code I was following was no longer valid swift:

layer.autoresizingMask = CAAutoresizingMask.LayerWidthSizable | CAAutoresizingMask.LayerHeightSizable
The first thing I tried was to initialize the CAAutoresizingMask manually, but this code looked ugly:

layer.autoresizingMask = CAAutoresizingMask( rawValue: CAAutoresizingMask.LayerWidthSizable.rawValue | CAAutoresizingMask.LayerHeightSizable.rawValue )
Then I discovered that OptionSetType objects implement the ArrayLiteralConvertible protocol. This gives an OptionSetType the ability to be initialized with array style syntax. The most concise way to initialize a CAAutoresizingMask object is as follows:

layer.autoresizingMask = [.LayerWidthSizable, .LayerHeightSizable]

No comments:

Post a Comment