Introduction
Functions are first-class in Swift so you can use them like any other value. This means you can store them, pass them around, and use them easily.
Functions are first-class in Swift so you can use them like any other value. This means you can store them, pass them around, and use them easily.
func greet(name: String) -> String { return "Hello, \(name)!" } let sayHello = greet // Assign function to a variable let message = sayHello("Alice") // Call function via variable
You can assign a function to a variable or constant.
You can pass functions as parameters or return them from other functions.
func add(a: Int, b: Int) -> Int { return a + b } let sumFunction = add let result = sumFunction(3, 4) // result is 7
func perform(operation: (Int, Int) -> Int, a: Int, b: Int) -> Int { return operation(a, b) } let multiply = { (x: Int, y: Int) in x * y } let product = perform(operation: multiply, a: 5, b: 6) // product is 30
func makeIncrementer() -> (Int) -> Int { return { number in number + 1 } } let increment = makeIncrementer() let newNumber = increment(7) // newNumber is 8
This program shows how to assign a function to a variable and call it.
func greet(name: String) -> String { return "Hello, \(name)!" } let sayHello = greet print(sayHello("Bob"))
Functions being first-class means they behave like any other value.
This feature helps make your code more flexible and reusable.
Functions can be stored in variables or constants.
Functions can be passed as arguments or returned from other functions.
This makes Swift code more powerful and easier to organize.
func multiplyByTwo(_ number: Int) -> Int {
return number * 2
}
let operation = multiplyByTwo
print(operation(5))func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
let sum = add(3, 4)
let operation = add(3, 4)
print(operation(5, 6))makeAdder(3)(5) should return 8.Pass the test and this pattern moves unknown