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 trialLauren Worthington
3,139 PointsHelp 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.
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
439 PointsHey 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
}
}
}
john lau
3,471 Pointsthe first code works perfectly well if you don't forget the "" on the string