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 Intermediate Swift Properties Computed Properties

Lauren Worthington
Lauren Worthington
3,139 Points

Help with computed properties

This is the question: In the editor I've created an enum to manage text presentation in my app. The enum members represent the three different text options. Your task is to create a computed property, style, that returns the correct style specifier provided below. For example Text.Headline.style should return the string "UIFontTextStyleHeadline".

I keep getting an error saying "Make sure you are declaring a computed property named style of type String" I definitely did that though so I'm not quite sure what the issue is.

enum.swift
let UIFontTextStyleHeadline = "UIFontTextStyleHeadline"
let UIFontTextStyleBody = "UIFontTextStyleBody"
let UIFontTextStyleFootnote = "UIFontTextStyleFootnote"

enum Text {
    case headline
    case body
    case footnote


    var style: String {

        switch self {
        case .headline:
            return UIFontTextStyleHeadline
        case .body:
            return UIFontTextStyleBody
        case .footnote:
            return UIFontTextStyleFootnote
        }
    }
}

2 Answers

Tom Makedonski
Tom Makedonski
439 Points

Hey Lauren, your way works fine if you are doing it in a Swift playground. But I think the problem lies in the fact that you need to make sure your constants are defined within the enum type, otherwise they are out of scope with respect to the enum class. When you define an enum, it's not like a closure or lambda where it can just take a variable from the surrounding scope. Try this:

enum Text {

    static let UIFontTextStyleHeadline = "UIFontTextStyleHeadline"
    static let UIFontTextStyleBody = "UIFontTextStyleBody"
    static let UIFontTextStyleFootnote = "UIFontTextStyleFootnote"

    case headline
    case body
    case footnote


    var style: String {

        switch self {
        case .headline:
            return Text.UIFontTextStyleHeadline
        case .body:
            return Text.UIFontTextStyleBody
        case .footnote:
            return Text.UIFontTextStyleFootnote
        }
    }
}

the first code works perfectly well if you don't forget the "" on the string