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 Object-Oriented Swift Properties Optional Property

Optional Property

let toy = Electronic(title: "RC Car", price: 79) toy.batteries = false if let batteries = toy.batteries { if batteries{ println("Batteries included")

I am not understanding why there is no output when toy.batteries = false. Can someone please explain this?

2 Answers

The default of any IF statement is to check if something is true. So for example, your code "if batteries { println("Batteries included") } can be read as "If batteries is TRUE then println "Batteries included", but you have no handle for if it is false.

If you were to rewrite your code to handle a case where batteries is false, it would look like this:

let toy = Electronic(title: "RC Car", price: 79) 
toy.batteries = false 
if let batteries = toy.batteries { 
     if batteries{
          println("Batteries included.")
     } else {
          println("Batteries not included.")
     }
}

The else statement will handle all cases where batteries is not true.

if argument is false it does not execute the code inside if statement. Very purpose of if statement is that execute the code if it is true otherwise leave it there and jump after if statement.