Functions are self-contained chunks of code that perform a specific task.
You give a function a name that identifies what it does, and this name is used to "call" the function to perform its task when needed.
Functions in Swift are highly flexible and expressive, making your code reusable, readable, and highly modular.
Let's dive into how to define and use functions in your Swift applications.
When you define a function, you can optionally define one or more named, typed values that the function takes as input.
These inputs are known as parameters.
You can also define a type of value that the function will pass back as output when it is done.
This output is known as its return type.
func greet() {
print("Hello, welcome to Swift!")
}
// Calling the function
greet()
Every function begins with the func keyword.
Functions can take parameters, which are essentially variables that are passed into the function when you call it.
You specify the parameter name and its data type inside the parentheses.
func sayHello(to person: String) {
print("Hello, \(person)!")
}
sayHello(to: "Akash")
Notice how readable the function call sayHello(to: "Akash") is!
A function can also return a value back to the code that called it.
You define a return type by placing an arrow -> followed by the data type after the parentheses.
func multiply(a: Int, b: Int) -> Int {
return a * b
}
let result = multiply(a: 5, b: 4)
print("The result is \(result)")
If the entire body of the function is a single expression, you can even omit the return keyword!
You can define a default value for any parameter in a function by assigning a value to the parameter after its type.
If a default value is defined, you can omit that parameter when calling the function.
func createGreeting(name: String, greeting: String = "Hello") {
print("\(greeting), \(name)!")
}
createGreeting(name: "John") // Uses default "Hello"
createGreeting(name: "Jane", greeting: "Welcome") // Overrides default
Swift allows you to give an argument label and a parameter name for each parameter.
The argument label is used when calling the function, while the parameter name is used inside the function's body.
By default, parameters use their parameter name as their argument label.
You can omit an argument label entirely by writing an underscore _ instead of an explicit argument label.
Which keyword is used to declare a new function in Swift?