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:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.