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!

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

Caitlin Quintero Weaver
Caitlin Quintero Weaver
5,221 Points

Efficiently using computed properties of enums with rawValues & string interpolation?

The code I've written is functional, but I'm not sure how I can just say:

to compute the variable style: given any member of the enum Text, get the rawValue & stick it in this string. return it.

The switch feels really inefficient here and I don't think it's enough of an improvement using the switch to assign the rawValue of the given case to some variable, then returning an interpolated string composed with that variable.

What's a better way?

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

enum Text: String {
    case Headline
    case Body
    case Footnote

    var style: String {
        switch self {
        case .Headline: return "UIFontTextStyle\(Text.Headline.rawValue)"
        case .Body: return "UIFontTextStyle\(Text.Body.rawValue)"
        case .Footnote: return "UIFontTextStyle\(Text.Footnote.rawValue)"

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Caitlin Quintero Weaver,

I understand what you're saying. I recently used this technique on a project of mine. I think your code is efficient. Maybe this example is a little misleading of the benefits. One benefit of this technique is that I was able to return a UIColor to generate different color themes in my app. Similar to one of the examples in the previous videos of this section. I thought this would be more efficient using rawValues (shorter and cleaner code), however, you can only use primitive types with rawValues. The type you want to use as a rawValue must be hashable. Whereas with this switch, you can return anything.

Good Luck