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

How to check optional is nil?

Referring to Optional Property i tried to print a comment when the optional parameter is nil.

my code is:

toy.batteries -------> value nil (i haven't save any value)

if toy.batteries != nil{ println("it's not nil") }else{ println("NIL!!!") }

I expect to print the else condition, but it doesn't. Could someone explain me why and how to get the result?

thanks (ps sorry for english)

2 Answers

Try

if let value = toy.batteries {
  print("Not nil")
} else {
  print("Nil")
}

The reason for this is because the property "batteries" would be an optional. To unwrap an optional you do the if let to unwrap.

Thanks David! I'm still programming basing my code on other kind of languages (php & actionscript ) and sometimes it's difficult to let go what you have apply for many years.

now it's clear best way to do it. :)