This Swift syntax quick reference covers the core language patterns students need when writing readable programs in Xcode or Swift Playgrounds. It helps grades 11 and 12 students remember how to declare values, choose types, write conditions, build loops, and organize code into reusable parts. A cheat sheet is useful because Swift has strict syntax, and small details like let versus var or optional unwrapping can change how a program behaves.
Key Facts
- Use let name = value for a constant and var name = value for a variable that can change.
- Common Swift types include Int for whole numbers, Double for decimals, String for text, Bool for true or false, and Character for one symbol.
- Use if condition { code } else { code } to choose between branches, and conditions must evaluate to a Bool.
- Use for item in collection { code } to loop through arrays, ranges, strings, or other sequences.
- Use while condition { code } when the number of loop repetitions is not known before the loop starts.
- Declare a function with func name(parameter: Type) -> ReturnType { return value }.
- An optional type is written as Type?, such as String?, and it can store either a value or nil.
- Use guard let value = optional else { return } or if let value = optional { code } to safely unwrap an optional.
Vocabulary
- Constant
- A named value declared with let that cannot be changed after it is assigned.
- Variable
- A named value declared with var that can be updated while the program runs.
- Optional
- A type that can hold either a normal value or nil to represent no value.
- Function
- A reusable block of code that can accept parameters, perform actions, and return a result.
- Array
- An ordered collection of values of the same type, accessed by zero-based index.
- Struct
- A custom value type that groups properties and methods into a reusable model.
Common Mistakes to Avoid
- Using let for a value that needs to change is wrong because Swift constants cannot be reassigned after initialization.
- Forgetting that array indexes start at 0 is wrong because the first element of items is items[0], not items[1].
- Force unwrapping an optional with ! without checking it is wrong because the program will crash if the optional contains nil.
- Writing a condition that is not a Bool is wrong because Swift does not treat numbers or strings as automatic true or false values.
- Leaving out argument labels in function calls is wrong when the function definition requires labels, because Swift uses labels as part of the call syntax.
Practice Questions
- 1 What is the output of this code: var score = 8; score += 5; print(score)?
- 2 What is the value of nums[2] after this code runs: let nums = [4, 7, 10, 13]?
- 3 Write a Swift function named square that takes an Int parameter named n and returns n multiplied by itself.
- 4 Explain why if let name = username { print(name) } is safer than print(username!) when username is a String?.