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
Fahiye Abdi
2,133 PointsUse time to determine outcome (SWIFT)
I'm practicing on my own and I'm having trouble making my code work. I attempted to use if statements but I know that if statements are "lazy" and once one of the conditions is true it will not execute the rest. Can someone help find a more efficient way of doing this. I included my code below.
Thank you.
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day , .Month , .Year], fromDate: date)
let year = components.year
let month = components.month
let day = components.day
let componentFHM = calendar.components([ .Hour, .Minute, .Second], fromDate: date)
let hour = componentFHM.hour
let minute = componentFHM.minute
if hour >= 17{
if minute >= 0{
if minute >= 30{
if hour <= 19{
if minute >= 0{
if minute <= 40{
// Enter print hello world
print("Helloworld") }}}}}}else{
//enter print Hello Mac
print("Hello Mac")}
1 Answer
Michael Reining
10,101 PointsHi Fahiye,
Some people refer to these nested if statements as the pyramid of doom. :-)
There are two good articles here of alternative approaches you can use with Swift 2.0.
https://www.natashatherobot.com/swift-guard-better-than-if/
http://austinzheng.com/2015/06/08/swift-2-control-flow/
I hope that helps,
Mike
PS: Thanks to the awesome resources on Team Treehouse, I launched my first app.
Now you can practice writing Swift code directly on your iPhone :-)