Swift & SwiftUI course › Session 1
Swift fundamentals
The Swift you need before SwiftUI makes sense: types, collections, closures and optionals, with the exam traps that catch people.
About 25 minutes · covers Data types, collections, operators, control flow, functions, closures, optionals
Open the interactive lesson (live previews, quizzes) →What you'll learn
- Choose let or var, and predict the type Swift infers
- Use arrays, sets, dictionaries and tuples, and know which return optionals
- Write switch statements Swift accepts (exhaustive, no fall-through)
- Read and write closures in every shorthand form
- Unwrap optionals five ways and know which one can crash
Contents
- Constants, variables and types
- Operators
- Collections: arrays, sets, dictionaries, tuples
- Control flow
- Functions
- Closures
- Higher-order functions
- Optionals
- Putting it together
Constants, variables and types
let declares a constant: it is set once and can't be reassigned. var declares a variable. Prefer let; Swift warns when a var is never changed.
let course = "Swift"
var year = 2014
year += 12
print(course, year)Output
Swift 2026let name = "Asha"
name = "Ravi"A let constant can't be reassigned. Swift reports this at compile time, so the program never runs.
| Type | Holds | Example |
|---|---|---|
| Int | Whole numbers (64-bit on modern devices) | 42 |
| Double | 64-bit decimals: the default for decimal literals | 3.14 |
| Float | 32-bit decimals: only when you write the type | let f: Float = 3.14 |
| String | Text | "Swift" |
| Character | One character: needs a type annotation | let c: Character = "A" |
| Bool | true or false | true |
Type inference: Swift works out the type from the value. Type annotation: you write it, let x: Int = 5. Swift is statically typed and type-safe: a variable's type never changes.
let a = 10
let b = 10.5
let c = "A"
print(type(of: a), type(of: b), type(of: c))Show the answer
Int Double StringType conversion
Swift never converts between number types for you. Convert explicitly. Converting a Double to Int truncates (drops the decimals). Converting a String to a number returns an optional, because the text might not be a number.
let count = 3
let price = 2.5
let total = count * priceInt and Double can't be mixed. Write Double(count) * price.
let count = 3
let price = 2.5
print(Double(count) * price)
print(Int(9.99))
print(Int(-9.99))
print(Int("123"))
print(Int("abc"))
print(String(42) + "!")Output
7.5
9
-9
Optional(123)
nil
42!Strings
let name = "Swift"
let version = 6
print("Hello, \(name) \(version)!")
print(name.count, name.isEmpty)
print(name.uppercased(), name.lowercased())
print(name.hasPrefix("Sw"), name.hasSuffix("ft"), name.contains("if"))
print(name.first!, name.last!)
print(String(name.reversed()))Output
Hello, Swift 6!
5 false
SWIFT swift
true true true
S t
tfiwSlet name = "Swift"
print(name[0])String has no integer subscript.
let word = "Swift"
print(word[word.startIndex])
let third = word.index(word.startIndex, offsetBy: 2)
print(word[third])
print(Array(word)[0])Output
S
i
SOperators
| Kind | Operators |
|---|---|
| Arithmetic | + - * / % |
| Compound assignment | += -= *= /= %= |
| Comparison | == != < > <= >= |
| Logical | && || ! |
| Ternary | condition ? a : b |
| Nil-coalescing | optional ?? fallback |
| Ranges | a...b (closed), a..<b (half-open), a... and ..<b (one-sided) |
| Identity (classes) | === and !== |
print(7 / 2)
print(7.0 / 2)
print(7 % 2)
print(-7 % 2)Show the answer
3
3.5
1
-1var count = 0
count++The ++ operator was removed in Swift 3.
let marks = 72
let result = marks >= 40 ? "Pass" : "Fail"
print(result)
for i in 1...3 { print("closed", i) }
for i in 1..<3 { print("half-open", i) }
print((0...10).count, (0..<10).count)Output
Pass
closed 1
closed 2
closed 3
half-open 1
half-open 2
11 10let big = Int.max
print(big &+ 1 == Int.min)Output
trueCollections: arrays, sets, dictionaries, tuples
| Array | Set | Dictionary | |
|---|---|---|---|
| Type | [Int] | Set<Int> | [String: Int] |
| Order | Kept | No order | No order |
| Duplicates | Allowed | Removed | Keys unique |
| Access | By index (a[0]) | Membership (contains) | By key (returns optional) |
| Elements must be | Any type | Hashable | Keys Hashable |
All three are value types: assigning one to another variable copies it. A let collection can't be changed at all.
Arrays
var fruits = ["Apple", "Mango", "Banana"]
fruits.append("Orange")
fruits.insert("Grapes", at: 1)
fruits[0] = "Kiwi"
fruits.remove(at: 2)
print(fruits)
print(fruits.count, fruits.first ?? "none", fruits.contains("Banana"))Output
["Kiwi", "Grapes", "Banana", "Orange"]
4 Kiwi truevar numbers = [3, 1, 2]
let sortedCopy = numbers.sorted()
print(numbers, sortedCopy)
numbers.sort()
print(numbers)Show the answer
[3, 1, 2] [1, 2, 3]
[1, 2, 3]Mutates in place (needs var) | Returns a new value |
|---|---|
sort() | sorted() |
reverse() | reversed() |
shuffle() | shuffled() |
append(_:) | + (a + [4]) |
var a = [1, 2, 3]
var b = a // a copy: arrays are value types
b.append(4)
print(a, b)
let empty: [Int] = []
print(empty.first, empty.isEmpty)Output
[1, 2, 3] [1, 2, 3, 4]
nil trueSets
var ids: Set = [1, 2, 2, 3, 3, 4]
print(ids.count)
ids.insert(5)
ids.remove(2)
print(ids.contains(3), ids.sorted())
let a: Set = [1, 2, 3]
let b: Set = [3, 4, 5]
print(a.union(b).sorted())
print(a.intersection(b).sorted())
print(a.subtracting(b).sorted())
print(a.symmetricDifference(b).sorted())Output
4
true [1, 3, 4, 5]
[1, 2, 3, 4, 5]
[3]
[1, 2]
[1, 2, 4, 5]Dictionaries
var marks = ["Asha": 90, "Ravi": 80]
marks["Ravi"] = 85 // update
marks["Meera"] = 75 // insert
print(marks["Asha"]) // Optional: the key might be missing
print(marks["Zoya"])
print(marks["Zoya", default: 0])
marks["Meera"] = nil // remove
print(marks.count)
for name in marks.keys.sorted() {
print(name, marks[name]!)
}Output
Optional(90)
nil
0
2
Asha 90
Ravi 85Tuples
A tuple groups a fixed number of values, which can have different types. Use it to return several values from a function. Use a struct instead when the data has meaning beyond one function call.
let student = (name: "Asha", age: 20, cgpa: 8.7)
print(student.name, student.1, student.cgpa)
let (name, _, cgpa) = student
print(name, cgpa)
let point = (3, 4)
print(point.0 + point.1)Output
Asha 20 8.7
Asha 8.7
7Try “Collections: arrays, sets, dictionaries, tuples” with live code →
Control flow
Conditions need no parentheses, but the braces are always required, even for one line. Conditions must be Bool: if count { } doesn't compile when count is an Int.
switch
- Exhaustive: every possible value must be handled, usually with
default. - No implicit fall-through: only the matching case runs, so no
breakneeded. - Every case needs at least one statement.
- Cases can match several values (
case 1, 2:), ranges, tuples, andwhereconditions. fallthroughruns the next case's body without checking its pattern.
func grade(_ marks: Int) -> String {
switch marks {
case 90...100: return "A"
case 75..<90: return "B"
case 40..<75: return "C"
case 0..<40: return "Fail"
default: return "Invalid"
}
}
print(grade(95), grade(80), grade(12), grade(140))
let point = (0, 5)
switch point {
case (0, 0): print("origin")
case (0, _): print("on the y-axis")
case (_, 0): print("on the x-axis")
case let (x, y) where x == y: print("diagonal")
default: print("somewhere else")
}Output
A B Fail Invalid
on the y-axislet n = 1
switch n {
case 1:
print("One")
fallthrough
case 2:
print("Two")
case 3:
print("Three")
default:
print("Other")
}Show the answer
One
Twolet day = 3
switch day {
case 1: print("Mon")
case 2: print("Tue")
}The switch isn't exhaustive: an Int has many more values. Add default:.
Loops
for i in stride(from: 10, through: 0, by: -5) { print(i) }
let names = ["Aman", "Ravi", "Priya"]
for (index, name) in names.enumerated() {
print(index, name)
}
for i in 1...10 where i % 4 == 0 { print("multiple of 4:", i) }
var i = 10
repeat {
print("repeat runs once:", i)
i += 1
} while i < 5Output
10
5
0
0 Aman
1 Ravi
2 Priya
multiple of 4: 4
multiple of 4: 8
repeat runs once: 10| while | repeat-while |
|---|---|
| Checks first (entry-controlled) | Checks after (exit-controlled) |
| May run 0 times | Runs at least once |
for i in 1...5 {
if i == 3 { continue }
if i == 5 { break }
print(i)
}Show the answer
1
2
4Functions
Each parameter has an argument label (used by the caller) and a parameter name (used inside). Write one name and it's both. Write _ as the label to call without one.
func greet(person name: String, from city: String = "Dehradun") -> String {
"Hello \(name) from \(city)" // one expression: return is implicit
}
print(greet(person: "Asha"))
print(greet(person: "Ravi", from: "Pune"))
func add(_ a: Int, _ b: Int) -> Int { a + b }
print(add(2, 3))Output
Hello Asha from Dehradun
Hello Ravi from Pune
5func add(a: Int, b: Int) -> Int { a + b }
print(add(2, 3))The labels are required: call it as add(a: 2, b: 3), or declare _ a: Int.
Several return values, variadic and inout
func stats(_ values: Int...) -> (min: Int, max: Int, sum: Int) {
(values.min()!, values.max()!, values.reduce(0, +))
}
let s = stats(5, 3, 9, 1)
print(s.min, s.max, s.sum)
func double(_ number: inout Int) {
number *= 2
}
var score = 21
double(&score)
print(score)Output
1 9 18
42- Variadic
Int...arrives inside the function as an[Int]. - Parameters are constants. To change the caller's variable, mark the parameter
inoutand pass&variable. - You can't pass a
letconstant or a literal as aninoutargument.
func double(_ number: inout Int) { number *= 2 }
let fixed = 5
double(&fixed)fixed is a constant, so it can't be passed as inout.
Closures
A closure is a block of code you can store in a variable and pass around, like a lambda. Functions are named closures. The syntax is { (parameters) -> ReturnType in statements }; the word in separates the signature from the body.
let multiply = { (a: Int, b: Int) -> Int in
return a * b
}
print(multiply(6, 7))
let numbers = [5, 2, 8, 1]
print(numbers.sorted(by: { (a: Int, b: Int) -> Bool in return a < b }))
print(numbers.sorted(by: { a, b in a < b }))
print(numbers.sorted(by: { $0 < $1 }))
print(numbers.sorted { $0 > $1 })
print(numbers.sorted(by: <))Output
42
[1, 2, 5, 8]
[1, 2, 5, 8]
[1, 2, 5, 8]
[8, 5, 2, 1]
[1, 2, 5, 8]| Shorthand step | What changed |
|---|---|
{ (a: Int, b: Int) -> Bool in return a < b } | Full form |
{ a, b in a < b } | Types inferred; one expression, so return is implicit |
{ $0 < $1 } | Shorthand argument names: $0 is the first argument |
sorted { $0 < $1 } | Trailing closure: written after the parentheses |
sorted(by: <) | An operator is a function too |
Capturing
func makeCounter() -> () -> Int {
var count = 0
return {
count += 1
return count
}
}
let next = makeCounter()
let other = makeCounter()
print(next(), next(), next(), other())Output
1 2 3 1The closure captures count and keeps it alive after makeCounter returns. Each call to makeCounter creates a separate count.
Escaping: a closure parameter is non-escaping by default: it must finish before the function returns. Mark it @escaping if the function stores it to call later (like a completion handler). Inside an escaping closure in a class, you must write self. explicitly.
Higher-order functions
A higher-order function takes a function or returns one. These replace most loops in Swift and SwiftUI code.
let numbers = [1, 2, 3, 4, 5]
print(numbers.map { $0 * 2 })
print(numbers.filter { $0 % 2 == 0 })
print(numbers.reduce(0, +))
print(numbers.reduce(10) { $0 + $1 })
print(numbers.contains { $0 > 4 })
print(numbers.first { $0 > 2 }!)
print(numbers.allSatisfy { $0 > 0 })
let texts = ["10", "hello", "20"]
print(texts.compactMap { Int($0) })
print(texts.map { Int($0) })
print([[1, 2], [3, 4]].flatMap { $0 })Output
[2, 4, 6, 8, 10]
[2, 4]
15
25
true
3
true
[10, 20]
[Optional(10), nil, Optional(20)]
[1, 2, 3, 4]| Function | Returns | Use it to |
|---|---|---|
map | Array of the same length | Transform every element |
filter | Array, maybe shorter | Keep matching elements |
reduce(initial, combine) | One value | Combine into a total |
compactMap | Array without the nils | Transform and drop failures |
flatMap | Flattened array | Join nested arrays |
forEach | Nothing | Side effects (like print) |
let words = ["swift", "ui", "code"]
let result = words.filter { $0.count > 2 }.map { $0.uppercased() }
print(result)Show the answer
["SWIFT", "CODE"]Optionals
An ordinary variable can never be nil. An optional (Int?) holds either a value or nil. It's an enum with two cases: .some(value) and .none.
var age: Int = 20
age = nilOnly optional types can be nil. Declare var age: Int? = 20.
let input: String? = "42"
let missing: String? = nil
// 1. Optional binding
if let text = input, let number = Int(text) {
print("Number:", number)
}
if let missing { print(missing) } else { print("missing is nil") }
// 2. Nil-coalescing
print(missing ?? "default")
// 3. Optional chaining: the result is optional too
print(input?.count, missing?.count)
// 4. Force unwrapping: only when you're certain
print(input!)
// 5. guard let: unwrap or leave early
func show(_ value: String?) {
guard let value else {
print("no value")
return
}
print("value:", value)
}
show(input)
show(missing)Output
Number: 42
missing is nil
default
Optional(2) nil
42
value: 42
no value| Technique | If the value is nil |
|---|---|
value! | Crash at runtime |
if let v = value | Skips the if body (runs else) |
guard let v = value else { return } | Runs the else, which must exit the scope |
value ?? fallback | Uses the fallback |
value?.property | The whole chain is nil |
| if let | guard let |
|---|---|
Unwrapped name exists only inside the if block | Unwrapped name exists after the guard, for the rest of the scope |
else is optional | else is required and must leave the scope (return, break, continue or throw) |
| Good for 'do this if present' | Good for early exit at the top of a function |
let x: Int? = nil
let y: Int? = 5
print(x ?? 50, y ?? 50)
print((y ?? 0) + 1)Show the answer
50 5
6Putting it together
A typical practical question: marks come in as text, some are invalid. Keep the valid ones, find who passed, and average the passing marks.
let marks = ["85", "35", "90", "Absent", "60"]
let valid = marks.compactMap { Int($0) }
let passed = valid.filter { $0 >= 40 }
let total = passed.reduce(0, +)
let average = passed.isEmpty ? 0.0 : Double(total) / Double(passed.count)
print("Valid:", valid)
print("Passed:", passed)
print("Average:", average)Output
Valid: [85, 35, 90, 60]
Passed: [85, 90, 60]
Average: 78.33333333333333It uses constants, arrays, closures, compactMap, filter, reduce, type conversion, the ternary operator and an empty check that avoids dividing by zero.
Exam traps
| Code or claim | What really happens |
|---|---|
let x = 10; x = 20 | Compile error: constants can't be reassigned |
7 / 2 | 3 (integer division) |
-7 % 2 | -1 (sign follows the left side) |
Int(4.9) and Int(-4.9) | 4 and -4 (truncates toward zero) |
Int("abc") | nil (the result is Int?) |
let x = 10.5 | Double, not Float |
1...5 and 1..<5 | 5 values and 4 values |
count++ | Compile error: no ++ in Swift |
Int.max + 1 | Runtime crash (overflow) |
Set([1, 1, 2]).count | 2 |
dict["missing"] | nil; present keys give Optional(value) |
array[99] on a short array | Runtime crash, not nil |
array.first on an empty array | nil |
sort() vs sorted() | sort() mutates; sorted() returns a copy |
switch without default on an Int | Compile error: not exhaustive |
fallthrough | Runs the next case without checking it |
repeat { } while false | Body runs once |
inout argument | Must pass &variable, never a let |
nilOptional! | Runtime crash |
name[0] on a String | Compile error: no integer subscript |
Viva questions and answers
Is Swift statically typed?
Yes. Every value's type is known at compile time and never changes. Type inference only means you don't always have to write the type.
What's the difference between let and var?
let is a constant that can't be reassigned; var can change. For value types, let also makes the whole value (including an array's elements) immutable.
What is an optional?
A type that holds either a value or nil. It's an enum, Optional<Wrapped>, with cases .some and .none. It makes 'no value' explicit, so the compiler forces you to handle it.
Name ways to unwrap an optional.
if let, guard let, ?? (nil-coalescing), ?. (optional chaining), ! (force unwrap), and switch on the optional.
if let vs guard let?
if let unwraps inside its block. guard let unwraps for the rest of the scope, and its else must exit. Use guard for early exits.
What is a closure?
A self-contained block of code that can be stored and passed around, and can capture variables from its surrounding scope. Functions are named closures.
What is a trailing closure?
A closure argument written after the call's parentheses, used when the closure is the last argument: numbers.sorted { $0 < $1 }.
What does @escaping mean?
The closure may be called after the function returns, so the function can store it. Closure parameters are non-escaping by default.
What is a higher-order function?
A function that takes or returns a function: map, filter, reduce, sorted(by:), compactMap.
map vs compactMap vs flatMap?
map transforms each element. compactMap transforms and removes nil results. flatMap transforms each element into a sequence and joins them.
Array vs Set vs Dictionary?
Array: ordered, allows duplicates, indexed. Set: unordered, unique, fast membership tests. Dictionary: unordered key-value pairs with unique keys.
Array vs tuple?
An array is a variable-length list of one type. A tuple is a fixed group of values that can have different types.
Are arrays value types or reference types?
Value types: assigning or passing one copies it (Swift copies lazily, only when one copy changes).
What is inout?
A parameter the function can modify, with the change visible to the caller. The caller passes &variable.
Why doesn't Swift have implicit fall-through?
To prevent the classic bug of a missing break. When you really want it, write fallthrough.
What happens on integer overflow?
A runtime trap (crash). Swift prefers crashing to silently wrong numbers. Wrapping operators &+, &- and &* exist when you want wrap-around.
Quiz
What type does Swift infer for
let x = 10.5?Show the answer
Double
Decimal literals default to
Double.What does this print?
Show the answer
2
Both are
Int, so it's integer division.How many values are in
0..<5?Show the answer
5
0, 1, 2, 3, 4: the half-open range excludes 5.
What is
Set([1, 1, 2, 3, 3]).count?Show the answer
3
A set removes duplicates: {1, 2, 3}.
What does a dictionary subscript return for a missing key?
Show the answer
nil
Subscripts return an optional; a missing key gives
nil.What does this print?
Show the answer
16
Starts at 10, then adds 1, 2 and 3.
What does this return?
Show the answer
[1, 3]
compactMapdrops thenilfromInt("abc").What happens when you force-unwrap a nil optional?
Show the answer
Runtime crash
The compiler can't know it's nil; the program traps when it runs.
Which statement unwraps an optional and requires the else branch to exit the scope?
Show the answer
guard let
Which symbol do you write before a variable passed to an
inoutparameter?Show the answer
&
Inside a closure, what is
$1?Show the answer
The second argument
Shorthand arguments count from
$0.Which loop always runs its body at least once?
Show the answer
repeat-while
What does this print?
Show the answer
50
What does this print?
Show the answer
2
Arrays are value types:
bis a copy.Which is true of Swift's
switch?Show the answer
It must be exhaustive
What does this print?
Show the answer
Optional(5)
Optional chaining always produces an optional.
What is
Int(-3.7)?Show the answer
-3
Converting to
Inttruncates toward zero.Which of these compiles?
Show the answer
let t = (1, "a", true)
Tuples can mix types. The others: two characters, non-optional nil, no
++.
← Exam essentials (start here) · Custom types and object-oriented Swift →
Practise this lesson interactively →