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 trialJason Anders
Treehouse Moderator 145,860 PointsWhat is the convention for expressing the conditions in an "if" statement? Parenthesis or not?
Both work and in the "Collections and Control Flow" Pasan Premaratne does both. In the first video...
if weather < 18 {}
But in the last video (FizzBuzz) challenge...
if (i % 3 == 0) && (i % 5 == 0) {}
else if (i % 3) {}
I've altered both to the opposites and it still compiles properly. So, which is the best or the 'right' way?
1 Answer
Martin Wildfeuer
Courses Plus Student 11,071 PointsHey there!
the convention with Swift is to not use parentheses with if statements, like in your first example.
if condition {
...
}
In the first line of your second example, however, it is not about the parentheses with if statements, but rather about increasing readability with operators:
if (i % 3 == 0) && (i % 5 == 0) { // Increase readability
} else if (i % 3) { // Not needed, like example 1
}
From Apple Docs: Explicit parenthesis:
Explicit Parentheses It is sometimes useful to include parentheses when they are not strictly needed, to make the intention of a complex expression easier to read.
So, to put it short: don't use parentheses for wrapping the condition, but use them whenever it increases readability with complex conditions.
Hope that helps :)
Jason Anders
Treehouse Moderator 145,860 PointsJason Anders
Treehouse Moderator 145,860 PointsThank you Martin Wildfeuer.
I wasn't sure if, maybe, certain expressions and/or grouped comparisons actually needed them for syntax or if it was just to makes things more clear for someone reading the code. Your answer makes sense and cleared that up for me.
Thanks again.