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

Keith Saft
Keith Saft
2,624 Points

SWIFT: Unwrapping conditional (from Struct Extra Credit)

In the Struct 'To Do' extra credit you create an enum called Status (.Doing, .Pending, . Complete) and a struct called Task which takes a description and uses a default status.

Everything works. However, when I try and get the status of a new task, I get a conditional error. :-(

var newTask = Task(description: "have lunch")

if let taskStatus = newTask.status { println("(taskStatus)") } else { println("nil") }

any thoughts as to what I am missing... Thanks!

Roberto Alicata
Roberto Alicata
Courses Plus Student 39,959 Points

Unwrap the conditional value whit the "?".

if let taskStatus = newTask.status as Status?

3 Answers

Keith Saft
Keith Saft
2,624 Points

Thank-you, Roberto! But it still doesn't quite get me what I was trying to get.... How do I get the current status of a Task? I put in the comments the notes I get back from the Playground.

var newTask = Task(description: "have lunch") // {description "have lunch", (Enum Value)} //

if let taskStatus = newTask.status as Status? {

println("(taskStatus)") // "(Enum Value)" //

} else {

println("nil")

}

Roberto Alicata
PLUS
Roberto Alicata
Courses Plus Student 39,959 Points

You must use the Printable interface on the enum then you must define a description getter method. Finally you can obtain the String value calling rawValue in the println.

enum Status: String, Printable {
    case Doing = "Doing"
    case Pending = "Pending"
    case Completed = "Completed"

    init() {
        self = .Pending

    }

    var description : String {
        get {
            return self.rawValue
        }
    }

}

struct Task {
    var description: String
    var status = Status()

    init(description: String){
        self.description = description
    }
}

var newTask = Task(description: "Have fun!")


if let taskStatus = newTask.status as Status? {
        println("\(taskStatus.rawValue)")
} else {
    println("nil")
}