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

Not sure how to complete this.

So I know I need to build a computed property, probably one that takes parameters for the constants built for the UIFontStyles. Not sure how to write it out or if I'm maybe heading in the wrong direction?

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

enum Text {
  case Headline
  case Body
  case Footnote
}

var style: String {

}

1 Answer

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

Just as classes and structs, enums can have properties. As the task descriptions says: for example Text.Headline.style should return the string "UIFontTextStyleHeadline". That indicates that style is a member of the Text enum. In code, that would be:

// With type annotation
let headlineStyle: String = Text.Headline.style // "UIFontTextStyleHeadline"

// Swift can infer the type String, so we can omit the type annotation
let headlineStyle = Text.Headline.style // "UIFontTextStyleHeadline"

So, depending on the enum, we want to return the corresponding style. That's where switch comes in handy. As style is a property of the Textenum, we can check for its current value with self.

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

enum Text {
  case Headline
  case Body
  case Footnote

  // A computed property is a var that does not store
  // a value, but returns a "computed" value
  var style: String {
    switch self {
    // Use the Text enum cases here to return the
    // corresponding constant, like UIFontTextStyleHeadline
    }
  }
}

Now all that's let is to define a case for each of the 3 enum members, returning the corresponding String in the body of style

Hint:

switch <value> {
case <enum>: return <value>
}

Hope that helps :)