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 trialGIUSEPPE GRAMMATICO
9,255 PointsHow 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
David Quach
1,479 PointsTry
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.
GIUSEPPE GRAMMATICO
9,255 PointsThanks 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. :)