Swift Syntax Basics
Prerequisites: How Swift code runs
A few rules cover most of what Swift code looks like.
One statement per line, no semicolons. Semicolons are only needed to put two statements on one line, which is rarely done.
Curly braces mark blocks of code:
if 10 > 5 {
print("Ten is bigger")
}
Ten is bigger
The braces are required, even around a single line. Conditions
don't need parentheses: if 10 > 5, not if (10 > 5).
Indentation is four spaces by convention. Swift doesn't require it, but it keeps code readable, and Xcode indents automatically.
Case matters. name and Name are different. The conventions:
lowerCamelCase for variables, constants, and functions (firstName,
calculateTotal), and UpperCamelCase for types (String,
ShoppingCart).
Spacing around operators must be balanced. a + b and a+b are
both fine, but a +b is an error, because Swift reads +b as a
single value.
Common mistakes
- Forgetting a closing brace — the compiler reports
expected '}'— or adding an extra one. - Unbalanced spacing such as
x =5. Put spaces on both sides of an operator, or neither.