You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Functions are fundamental building blocks in Swift. This lesson covers function declaration, parameters, return types, closures, and higher-order functions.
func greet(person: String) -> String {
return "Hello, \(person)!"
}
let message = greet(person: "Alice") // "Hello, Alice!"
func printGreeting(for name: String) {
print("Hello, \(name)!")
}
func minMax(array: [Int]) -> (min: Int, max: Int)? {
guard !array.isEmpty else { return nil }
var currentMin = array[0]
var currentMax = array[0]
for value in array[1...] {
if value < currentMin { currentMin = value }
if value > currentMax { currentMax = value }
}
return (min: currentMin, max: currentMax)
}
if let result = minMax(array: [3, 1, 4, 1, 5, 9]) {
print("Min: \(result.min), Max: \(result.max)")
}
Swift functions have both an argument label (used when calling) and a parameter name (used inside the function):
func move(from source: String, to destination: String) {
print("Moving from \(source) to \(destination)")
}
move(from: "London", to: "Paris")
Use _ to allow callers to omit the label:
func multiply(_ a: Int, _ b: Int) -> Int {
return a * b
}
let result = multiply(3, 4) // no argument labels needed
func greet(person: String, greeting: String = "Hello") -> String {
return "\(greeting), \(person)!"
}
greet(person: "Alice") // "Hello, Alice!"
greet(person: "Alice", greeting: "Hi") // "Hi, Alice!"
func average(_ numbers: Double...) -> Double {
let total = numbers.reduce(0, +)
return total / Double(numbers.count)
}
let avg = average(1.0, 2.0, 3.0, 4.0) // 2.5
By default, function parameters are constants. Use inout to allow modification:
func swapValues(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
var x = 10
var y = 20
swapValues(&x, &y)
print("x: \(x), y: \(y)") // x: 20, y: 10
Functions in Swift are first-class citizens with their own types:
func add(_ a: Int, _ b: Int) -> Int { return a + b }
func subtract(_ a: Int, _ b: Int) -> Int { return a - b }
// Function type: (Int, Int) -> Int
var operation: (Int, Int) -> Int = add
print(operation(5, 3)) // 8
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.