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

Why is it asking me for a default clause?

I aim switching on self and I am including both cases Done and Edit. Why is swift asking me for a default clause?

import Foundation

enum UIBarButtonStyle {
    case Done
    case Plain
    case Bordered
}

class UIBarButtonItem {

    var title: String?
    let style: UIBarButtonStyle
    var target: AnyObject?
    var action: Selector

    init(title: String?, style: UIBarButtonStyle, target: AnyObject?, action: Selector) {
        self.title = title
        self.style = style
        self.target = target
        self.action = action
    }
}

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

    func toUIBarButtonItem() -> UIBarButtonItem {

        switch self {

        case Button.Done("Done"): return UIBarButtonItem(title: "Done", style: UIBarButtonStyle.Done, target: nil, action: nil)

        case Button.Edit("Edit"): return UIBarButtonItem(title: "Edit", style: UIBarButtonStyle.Plain, target: nil, action: nil)

           } // error here: switch needs to be exhaustive
    }
}

1 Answer

That is because your switch statement does not cover all possible cases, but only two:

  • A button of type .Done with associated string value "Done"
  • A button of type .Edit with associated string value "Edit"
case Button.Done("Done"): // ...
case Button.Edit("Edit"): // ...

Therefore, you had to add a default case to cover all the other possible String values you could potentially init your enum with.

However, what you probably want to achieve is using the title you init your enum with as the title of your button. So instead of using a "hardcoded" title, you could use the associated string which also covered all possible cases. This way, you wouldn't need a default either:

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

Hope that helps :)

Yes, this solves my issue. Thanks :)

You are welcome, glad I could help :)