ViewLab

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

Contents

  1. Constants, variables and types
  2. Operators
  3. Collections: arrays, sets, dictionaries, tuples
  4. Control flow
  5. Functions
  6. Closures
  7. Higher-order functions
  8. Optionals
  9. 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 2026
This doesn't compile
let name = "Asha"
name = "Ravi"

A let constant can't be reassigned. Swift reports this at compile time, so the program never runs.

TypeHoldsExample
IntWhole numbers (64-bit on modern devices)42
Double64-bit decimals: the default for decimal literals3.14
Float32-bit decimals: only when you write the typelet f: Float = 3.14
StringText"Swift"
CharacterOne character: needs a type annotationlet c: Character = "A"
Booltrue or falsetrue

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.

What does this print?
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 String

Type 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.

This doesn't compile
let count = 3
let price = 2.5
let total = count * price

Int 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
tfiwS
This doesn't compile
let 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
S

Try “Constants, variables and types” with live code →

Operators

KindOperators
Arithmetic+ - * / %
Compound assignment+= -= *= /= %=
Comparison== != < > <= >=
Logical&& || !
Ternarycondition ? a : b
Nil-coalescingoptional ?? fallback
Rangesa...b (closed), a..<b (half-open), a... and ..<b (one-sided)
Identity (classes)=== and !==
What does this print?
print(7 / 2)
print(7.0 / 2)
print(7 % 2)
print(-7 % 2)
Show the answer
3
3.5
1
-1
This doesn't compile
var 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 10
let big = Int.max
print(big &+ 1 == Int.min)

Output

true

Try “Operators” with live code →

Collections: arrays, sets, dictionaries, tuples

ArraySetDictionary
Type[Int]Set<Int>[String: Int]
OrderKeptNo orderNo order
DuplicatesAllowedRemovedKeys unique
AccessBy index (a[0])Membership (contains)By key (returns optional)
Elements must beAny typeHashableKeys 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 true
What does this print?
var 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 true

Sets

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 85

Tuples

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
7

Try “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

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-axis
What does this print?
let n = 1
switch n {
case 1:
    print("One")
    fallthrough
case 2:
    print("Two")
case 3:
    print("Three")
default:
    print("Other")
}
Show the answer
One
Two
This doesn't compile
let 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 < 5

Output

10
5
0
0 Aman
1 Ravi
2 Priya
multiple of 4: 4
multiple of 4: 8
repeat runs once: 10
whilerepeat-while
Checks first (entry-controlled)Checks after (exit-controlled)
May run 0 timesRuns at least once
What does this print?
for i in 1...5 {
    if i == 3 { continue }
    if i == 5 { break }
    print(i)
}
Show the answer
1
2
4

Try “Control flow” with live code →

Functions

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
5
This doesn't compile
func 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
This doesn't compile
func double(_ number: inout Int) { number *= 2 }
let fixed = 5
double(&fixed)

fixed is a constant, so it can't be passed as inout.

Try “Functions” with live code →

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 stepWhat 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 1

The 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.

Try “Closures” with live code →

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]
FunctionReturnsUse it to
mapArray of the same lengthTransform every element
filterArray, maybe shorterKeep matching elements
reduce(initial, combine)One valueCombine into a total
compactMapArray without the nilsTransform and drop failures
flatMapFlattened arrayJoin nested arrays
forEachNothingSide effects (like print)
What does this print?
let words = ["swift", "ui", "code"]
let result = words.filter { $0.count > 2 }.map { $0.uppercased() }
print(result)
Show the answer
["SWIFT", "CODE"]

Try “Higher-order functions” with live 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.

This doesn't compile
var age: Int = 20
age = nil

Only 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
TechniqueIf the value is nil
value!Crash at runtime
if let v = valueSkips the if body (runs else)
guard let v = value else { return }Runs the else, which must exit the scope
value ?? fallbackUses the fallback
value?.propertyThe whole chain is nil
if letguard let
Unwrapped name exists only inside the if blockUnwrapped name exists after the guard, for the rest of the scope
else is optionalelse 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
What does this print?
let x: Int? = nil
let y: Int? = 5
print(x ?? 50, y ?? 50)
print((y ?? 0) + 1)
Show the answer
50 5
6

Try “Optionals” with live code →

Putting 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.33333333333333

It uses constants, arrays, closures, compactMap, filter, reduce, type conversion, the ternary operator and an empty check that avoids dividing by zero.

Try “Putting it together” with live code →

Exam traps

Code or claimWhat really happens
let x = 10; x = 20Compile error: constants can't be reassigned
7 / 23 (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.5Double, not Float
1...5 and 1..<55 values and 4 values
count++Compile error: no ++ in Swift
Int.max + 1Runtime crash (overflow)
Set([1, 1, 2]).count2
dict["missing"]nil; present keys give Optional(value)
array[99] on a short arrayRuntime crash, not nil
array.first on an empty arraynil
sort() vs sorted()sort() mutates; sorted() returns a copy
switch without default on an IntCompile error: not exhaustive
fallthroughRuns the next case without checking it
repeat { } while falseBody runs once
inout argumentMust pass &variable, never a let
nilOptional!Runtime crash
name[0] on a StringCompile 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

  1. What type does Swift infer for let x = 10.5?

    Show the answer

    Double

    Decimal literals default to Double.

  2. What does this print?

    Show the answer

    2

    Both are Int, so it's integer division.

  3. How many values are in 0..<5?

    Show the answer

    5

    0, 1, 2, 3, 4: the half-open range excludes 5.

  4. What is Set([1, 1, 2, 3, 3]).count?

    Show the answer

    3

    A set removes duplicates: {1, 2, 3}.

  5. What does a dictionary subscript return for a missing key?

    Show the answer

    nil

    Subscripts return an optional; a missing key gives nil.

  6. What does this print?

    Show the answer

    16

    Starts at 10, then adds 1, 2 and 3.

  7. What does this return?

    Show the answer

    [1, 3]

    compactMap drops the nil from Int("abc").

  8. 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.

  9. Which statement unwraps an optional and requires the else branch to exit the scope?

    Show the answer

    guard let

  10. Which symbol do you write before a variable passed to an inout parameter?

    Show the answer

    &

  11. Inside a closure, what is $1?

    Show the answer

    The second argument

    Shorthand arguments count from $0.

  12. Which loop always runs its body at least once?

    Show the answer

    repeat-while

  13. What does this print?

    Show the answer

    50

  14. What does this print?

    Show the answer

    2

    Arrays are value types: b is a copy.

  15. Which is true of Swift's switch?

    Show the answer

    It must be exhaustive

  16. What does this print?

    Show the answer

    Optional(5)

    Optional chaining always produces an optional.

  17. What is Int(-3.7)?

    Show the answer

    -3

    Converting to Int truncates toward zero.

  18. 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 →