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 Enumerations and Optionals in Swift Introduction to Enumerations Enum Methods

how to create function with UIBarButtonItem initializer

can you please help me complete this challenge

buttons.swift
// Example of UIBarButtonItem instance
// let someButton = UIBarButtonItem(title: "A Title", style: .plain, target: nil, action: nil)
enum UIBarButtonStyle {
case done
case plain
}

enum BarButton {
    case done(title: String, style: UIBarButtonStyle, target: nil, action: nil)
    case edit(title: String, style: UIBarButtonStyle, target: nil, action: nil)

    func button() -> UIBarButtonItem {
    switch self{
    case .done("done", .done, nil, nil): return UIBarButtonItem(title: BarButton.done, style: UIBarButtonStyle.done, target: nil, action: nil)
    case .edit: return UIBarButtonItem(title: BarButton.edit, style: UIBarButtonStyle.plain, target: nil, action: nil)
    }

    }
}

let done = BarButton.done(title: "Save")
let button = done.button()

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Casandra Hayward,

Inside of our enum BarButton, the instance method, button(), will switch on self and return an instance of UIBarButtonItem depend on the case.

The challenge says that the target and action parameters for the UIBarButtonItem can be nil. This means to create our instance we only need a title, String, and style, UIBarButtonStyle.

There are two possible case for our BarButton enum: done and edit. We will use a UIBarButtonStyle.plain in the case of .edit and a UIBarButtonStyle.done in the case of .done.

To get the title value we will use the associated String value for each case. We can extract this value by using a switch statement.

Here's the code:

enum UIBarButtonStyle {
case done
case plain
}

enum BarButton {
    case done(title: String)
    case edit(title: String)

    func button() -> UIBarButtonItem {
        switch self{
        case .done(let title): 
            /* We can just use .done and .plain instead of
                writing the enum type prefix */
            return UIBarButtonItem(title: title, style: .done, target: nil, action: nil)
        case .edit(let title): 
            return UIBarButtonItem(title: title, style: .plain, target: nil, action: nil)
        }
    }
}

let done = BarButton.done(title: "Save")
let button = done.button()

Good Luck

thank you