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

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