Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Industry standard for curly braces [closed]

In Swift, I am trying to figure out whether I should do

if(true)
{
    //stuff
}
else
{
    //other stuff
}

Or

if(true){
    //stuff
} else{
    //other stuff
}

I know that technically it doesn't make a difference, but I was wondering what the industry standard was, and why the standard is...the standard.

like image 474
Daniel Smith Avatar asked Mar 10 '15 01:03

Daniel Smith


2 Answers

Bracket style is usually a matter of opinion.

However, in this case, there is something to go by. Apple uses the second syntax you have provided exclusively in all of its documentation, with one distinction for Swift: parentheses.

From The Swift Programming Language Guide – Control Flow:

In addition to for-in loops, Swift supports traditional C-style for loops with a condition and an incrementer...

Here’s the general form of this loop format:

for initialization; condition; increment {
    statements
}

Semicolons separate the three parts of the loop’s definition, as in C. However, unlike C, Swift doesn’t need parentheses around the entire “initialization; condition; increment” block.

In other words, you don't need parentheses around your conditional statements (in any type of loop or logic statement), and this is typically how Apple uses it in the documentation.

So, in the sample you have provided, Apple would use this style (note the spacing between the curly braces as well):

if condition {
    // Stuff
} else {
    // Other stuff
}

Some other examples from the docs:

// While loops
while condition {
    statements
}

// Do-while loops
do {
    statements
} while condition

// Switch statements
switch some value to consider {
case value 1:
    respond to value 1
case value 2,
value 3:
    respond to value 2 or 3
default:
    otherwise, do something else
}
like image 194
AstroCB Avatar answered Nov 14 '22 23:11

AstroCB


I have worked for different company and each of them is using different standard/coding rules.

When it comes to Apple and looking at their Swift documentation, it looks like they are using your second option.

like image 23
Jérôme Avatar answered Nov 14 '22 23:11

Jérôme