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

Enum & 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

I 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

hm... I inserted your changes but it doesn't really work. I still get "The task Learn Swift is (Enum Value)"...

hmm 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)"

That worked! Thanks for your fast help!

cool. 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