Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.