Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.


Swift extensions: OptionSetType factory

In Swift 2.0 Apple has introduced the OptionSetType, this basic type is used for options parameters into the Cocoa API's. As an example I will use NSDirectoryEnumerationOptions

Unfortunately I have not been able to discover (so far) a nice way to assemble such options.
I thus end up coding this as:

let dirScanOptions = NSDirectoryEnumerationOptions(rawValue :
   NSDirectoryEnumerationOptions.SkipsHiddenFiles.rawValue |
   NSDirectoryEnumerationOptions.SkipsPackageDescendants.rawValue |

That works, but is more verbose than necessary imo.

I thus wrote a little extension that gives me a factory method to create these kind of values as follows:

let dirScanOptions = NSDirectoryEnumerationOptions.withOptions(.SkipsHiddenFiles, .SkipsPackageDescendants, .SkipsSubdirectoryDescendants)

The extension itself is simple enough:

extension OptionSetType where RawValue : BitwiseOperationsType {
    static func withOptions(items: Self...) -> Self {
        var result = items[0]
        for item in items {
            result = Self(rawValue: (result.rawValue | item.rawValue))
        return result


Since the actual 'or'-ing is rather fast, I have skipped the effort of starting at the second item. Or-ing the first item with itself will not change the result and could be even faster than excluding the first item from the loop.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.


  1. let dirScanOptions: NSDirectoryEnumerationOptions = [.SkipsHiddenFiles, .SkipsPackageDescendants, .SkipsSubdirectoryDescendants]