OptionSetType Swift 2 Error: Nil is not compatible with expected argument

If you've been using Swift 1.2 or earlier, or you're an experienced Objective-C developer you'll discover using some APIs is different. 

Apple has been revamping all the APIs in Swift + Objective-C to support the latest Swift 2 language.

Apple has added Generics, Error Handling, and the OptionSetType which will change a large portion of the APIs – especially anything that takes option/setting flags.

Code Massaging

Moving forward you're going to have to massage your existing code, or your old programming habits to work with the new APIs.

I highly recommend opening a Documentation window (Shift + Command + 0) with Swift, since the Quick Help fails to work when you have a syntax error – something that didn't happened in Objective-C.

OptionSetType

The animatWithDuration: API that works with the spring physics has changed it's options: parameter to the new OptionSetType.

var myFirstLabel: UILabel!

func tapped(gesture: UITapGestureRecognizer) {
    UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.0, options: nil, animations: {
        
        self.myFirstLabel.center = CGPoint(x: 100, y:40 + 200)
        
        }, completion: nil)
}

In Xcode 6 this code works with Swift 1.2 or lower, however if you run it in Xcode 7 + Swift 2 you'll get the following Error.

Swift 2 Errors

You might see either of these errors, depending on the version of Xcode. Error messages are continuing to evolve, some are even more helpful in diagnosing the problem.

ViewController.swift Nil is not compatible with expected argument type 'UIViewAnimationOptions'

ViewController.swift Cannot invoke 'animateWithDuration' with an argument list of type '(Double, delay: Double, usingSpringWithDamping: Double, initialSpringVelocity: Double, options: nil, animations: () -> _, completion: nil)'

Solution

The error is because the type for the options: parameter is wrong – you'll have to pass in an empty OptionSetType in order to compile.

nil should be replaced with []

Apple has changed options for many existing APIs, instead of being a NS_OPTIONS bitmask, in Swift 2.1+ they are treated as a Set in syntax and behavior. To pass no options (i.e. nil) you pass the empty set: [ ]

UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.0, options: [], animations: {
    
    self.myFirstLabel.center = CGPoint(x: 100, y:40 + 200)
    
    }, completion: nil)

Follow me

Have you seen any strange error messages?

Send a Tweet to @PaulSolt