In Swift, a function is a self-contained block of code that performs a specific task. Functions help in defining reusable code blocks and make the code more modular, readable, and maintainable. Functions can have one or more parameters and can also return values.
A Swift function is defined using the func keyword followed by the function name, parameters, and the return type (if any).
func greet(name: String) {
print("Hello, \(name)!")
}
greet(name: "John")
func addNumbers(a: Int, b: Int) -> Int {
return a + b
}
let result = addNumbers(a: 2, b: 3)
Functions in Swift can have parameters that can be either of constant or variable type. Also, there are two types of parameters:
func multiplyNumbers(a: Int, b: Int = 2) -> Int {
return a * b
}
let result1 = multiplyNumbers(a: 3) // Returns 6
let result2 = multiplyNumbers(a: 3, b: 4) // Returns 12
A function in Swift can return a value or void (if it doesn't return any value). The return type of a function is specified using the arrow -> followed by the return type.
func isEven(number: Int) -> Bool {
if number % 2 == 0 {
return true
}
else {
return false
}
}
let result = isEven(number: 4) // Returns true
In Swift, functions are the first-class citizens, this means that functions can be assigned to variables/constants, passed as parameters to other functions, and can also be returned from functions.
func subtractNumbers(a: Int, b: Int) -> Int {
return a - b
}
var mathFunction: (Int, Int) -> Int = addNumbers
print(mathFunction(2, 3)) // Prints 5
mathFunction = subtractNumbers
print(mathFunction(3, 2)) // Prints 1
Swift allows defining multiple functions with the same name but with different parameters (type or number).
func sayHello() {
print("Hello, world!")
}
func sayHello(name: String) {
print("Hello, \(name)!")
}
sayHello() // Prints "Hello, world!"
sayHello(name: "Joe") // Prints "Hello, Joe!"
Functions in Swift returns a value by default, but sometimes, we may not need the return value in our code. In such cases, we can use the @discardableResult attribute to ignore the return value.
@discardableResult
func printMessage(message: String) -> Bool {
print(message)
return true
}
printMessage(message: "This is a message") // Prints "This is a message"
Functions in Swift are a powerful tool to define reusable code blocks that perform specific tasks. They can have one or more parameters, a return value, and can also use named or default parameters. Functions can be assigned to variables/constants, passed as parameters, and returned from other functions. Swift supports function overloading and the @discardableResult attribute to ignore a function's return value.