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 Methods on Enumerations

About functions

I did this and it works

enum Text {
  case headline
  case body
  case footnote

    func style () -> String {
        switch self {
        case .headline: return "UIFontTextStyleHeadline"
        case .body: return "UIFontTextStyleBody"
        case .footnote: return "UIFontTextStyleFootnote"
        }
    }
}

print(Text.footnote.style())

it prints:

UIFontTextStyleFootnote

However when I do the next it doesn't work.

enum Text: String {
  case headline = "UIFontTextStyleHeadline"
  case body = "UIFontTextStyleBody"
  case footnote = "UIFontTextStyleFootnote"

    func style (_ value: Text ) -> String {
        switch value {
        case .headline: return Text.headline.rawValue
        case .body: return Text.body.rawValue
        case .footnote: return Text.footnote.rawValue
        }
    }
}

print(Text.style(.body))

It prints:

(function)

Please I am really curious about this, why this happens?

1 Answer

Jhoan Arango
Jhoan Arango
14,575 Points

Hello,

Sorry it took a few days to get to you, I was in vacations.

So essentially what you are doing should work in theory, but there Is one thing missing.

Noticed how in the first snippet you called : print(Text.footnote.style()) this is correct since you are creating an instance of Text and then calling its method.

ON the second snippet you are NOT creating an intense of Text, therefore you are not able to call the "method" instead you are creating a closure. When I say creating a closure is because when you call Text.style() it will return that function and you can set it on a variable if you wanted. This variable will be that closure. Hence the reason why is printing "(Function)".

What you need to do is what you did on the first snippet:

enum Text: String {

  case headline = "UIFontTextStyleHeadline"
  case body     = "UIFontTextStyleBody"
  case footnote = "UIFontTextStyleFootnote"

    func style (_ value: Text) -> String {
        switch value {
        case .headline : return Text.headline.rawValue
        case .body     : return Text.body.rawValue
        case .footnote : return Text.footnote.rawValue
        }
    }
}

print(Text.headline.style(.body)) // prints "UIFontTextStyleBody"

Hope this helps you, let me know if you need more help