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
Tina Egolf
1,807 PointsEnum & Struct Exam: How can I return the actual value of the default enum?
I just completed the final exam of the Enum & Struct (iOS Swift) course. The challenge was to construct an enum and a struct for a tasks app. My answer was correct and the video showed the same result but I wonder, how would I get the actual value of the initialized enum returned? I only get (Enum Value) when I try to print:
enum Status {
case Open, Pending, Completed
init() {
self = .Open
}
}
struct Task {
var description: String
var status = Status()
init(description: String){
self.description = description
}
func writeTasks()->String {
return "The task \(self.description) is \(self.status)"
}
}
var firstTask = Task(description: "Learn Swift")
print(firstTask.writeTasks())
And the result is
"The task Learn Swift is (Enum Value) "
....
How do it get it to print "The task Learn Swift is Open" ...?
1 Answer
Stone Preston
42,016 PointsI dont think you can print the name of the enum case like that. I think you will have to use a raw value for that and adopt the printable protocol and implement the description method:
enum Status : String, Printable {
case Open = "Open", Pending = "Pending", Completed = "Completed"
init() {
self = .Open
}
var description : String {
get {
return self.rawValue
}
}
}
then you can print out the value of the status property of your struct:
func writeTasks()->String {
return "The task \(self.description) is \(self.status)"
}
source: This Stackoverflow post
Tina Egolf
1,807 PointsTina Egolf
1,807 Pointshm... I inserted your changes but it doesn't really work. I still get "The task Learn Swift is (Enum Value)"...
Stone Preston
42,016 PointsStone Preston
42,016 Pointshmm apparently The Printable protocol does not currently work in Playgrounds.
try printing the raw value out yourself and see what you get:
return "The task \(self.description) is \(self.status.rawValue)"Tina Egolf
1,807 PointsTina Egolf
1,807 PointsThat worked! Thanks for your fast help!
Stone Preston
42,016 PointsStone Preston
42,016 Pointscool. the first way I posted should work outside of playground, but since Printable doesnt work in playgrounds you have to print the rawValue out yourself. glad you got it working