Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift 2.0 Enumerations and Optionals Introduction to Enumerations Enum Methods

Jonathan Martínez
Jonathan Martínez
13,375 Points

nil is not compatible with expected argument type Selector??

So, I had a hard time trying to figure this out (mainly because I take all Code Challenges to a Playground, do a bit of testing and when I'm finished, I copy the Playground to the Code Challenge)

enum Button {
  case Done(String)
  case Edit(String)

  func toUIBarButtonItem() -> UIBarButtonItem {
    switch self {
    case .Done(let title) : return UIBarButtonItem(title: title, style: UIBarButtonStyle.Done, target: nil, action: nil)
    case .Edit(let title) : return UIBarButtonItem(title: title, style: UIBarButtonStyle.Plain, target: nil, action: nil)
    }
  }
}

let done = Button.Done("Done")
let doneButton = done.toUIBarButtonItem()

This is working, but not on Playgrounds. When you pass nil to action, the compiler threws nil is not compatible with expected argument type 'Selector'

How is that it won't work on Playground but it will pass as correct here?

1 Answer

David Lin
David Lin
35,864 Points
UIBarButtonItem(title: String?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector)

As you can see in UIBarButtonItem's signature, the action parameter is a non-optional Selector type. So, you are correct that action cannot be nil.

My guess is that since Selector had not yet been taught at this stage in the course, the instructors just said to use nil as a value as a matter of expediency.

Also, you may have noticed that TH's code checking algorithm is not based on an actual Swift compiler, because it often rejects implementations which would otherwise satisfy the coding requirements.