Swift: Functions & Closures
What you will learn
How to define functions, Swift's unique argument labels, and closures (lambdas).
Basic function
func greet(name: String) -> String {
return "Hello, \(name)!"
}
let msg = greet(name: "Alice") // Hello, Alice!
Swift uses -> to separate parameters from the return type. String interpolation uses \(expr).
Parameter labels — internal vs external
Swift lets you give each parameter an external label (for the caller) and an internal name (for the function body):
// External label "to", internal name "recipient"
func sendMessage(to recipient: String, body: String) {
print("To \(recipient): \(body)")
}
sendMessage(to: "Alice", body: "Hi!") // caller uses external labels
To omit the external label, use _:
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
add(3, 5) // no parameter labels needed
Default parameters
func greet(_ name: String, greeting: String = "Hello") -> String {
return "\(greeting), \(name)!"
}
greet("Alice") // Hello, Alice!
greet("Bob", greeting: "Hi") // Hi, Bob!
Closures (blocks of code)
Closures are self-contained blocks of functionality — Swift's version of lambdas:
let numbers = [1, 2, 3, 4, 5]
// Full closure syntax
let doubled = numbers.map({ (n: Int) -> Int in
return n * 2
})
// Trailing closure (most idiomatic)
let tripled = numbers.map { $0 * 3 }
// Named parameter
let evens = numbers.filter { n in n.isMultiple(of: 2) }
$0, $1, etc. are shorthand argument names.
Common mistakes
- Forgetting the external label when calling a function — most Swift functions require argument labels
- Using
$0when a named parameter would be clearer - Adding a semicolon at the end of lines — Swift doesn't require them
- Confusing
\(expr)with#(expr)— interpolation uses backslash-parens
Quick check below!