Swift Functions Essentials
Function Basics
What Are Functions?
Think of a function as a recipe. A recipe lists a set of instructions to achieve a specific task, like baking a cake. You can use that recipe over and over again. In programming, a function is a named block of code that performs a specific task.
Instead of writing the same lines of code every time you need to do something, you can write it once inside a function and then just "call" that function by its name whenever you need it. This keeps your code organized and easy to read. It's a core principle of programming: Don't Repeat Yourself (DRY).
Functions help you break down large, complex problems into smaller, manageable pieces. Each piece can be its own function, making your program easier to build, test, and fix.
Building and Calling Functions
In Swift, you declare a function using the func keyword, followed by the function's name and a pair of parentheses (). The code that the function will execute is placed inside curly braces {}.
func sayHello() {
print("Hello, world!")
}
We've just defined a function named sayHello. But defining it doesn't run the code inside. To execute the code, you need to call the function. You do this by writing its name followed by parentheses.
// This calls the function and runs its code.
sayHello()
When you run this line, "Hello, world!" will be printed to the console. You can call sayHello() as many times as you want, and it will perform its task each time.
Using Parameters
What if you want a function to be a bit more flexible? For example, instead of just saying hello to the world, you want to greet a specific person. You can do this using parameters, which are like inputs for your function.
You define parameters inside the parentheses when you declare the function. You give each parameter a name and a type.
// 'person' is the parameter name.
// 'String' is the parameter type.
func greet(person: String) {
print("Hello, \(person)!")
}
Now, when you call this function, you must provide a value (called an argument) for the person parameter. The argument's type must match the parameter's type. In this case, it must be a String.
greet(person: "Maria") // Prints "Hello, Maria!"
greet(person: "David") // Prints "Hello, David!"
You can also have functions with multiple parameters, separated by commas.
func printPersonalInfo(name: String, age: Int) {
print("My name is \(name) and I am \(age) years old.")
}
printPersonalInfo(name: "Alex", age: 30)
Getting Values Back
Sometimes, you don't just want a function to perform an action; you want it to compute a value and give it back to you. This output is called a return value.
To declare that a function returns a value, you add an arrow -> followed by the data type of the value it will return. Inside the function, you use the return keyword to send the value back.
A function can only return one value, and its type must match the return type specified in the function's definition.
Let's create a function that adds two numbers and returns the result.
// This function takes two Ints and returns an Int.
func addTwoNumbers(a: Int, b: Int) -> Int {
let sum = a + b
return sum
}
When you call this function, you can assign its return value to a variable or constant to use it later.
let result = addTwoNumbers(a: 5, b: 3)
print(result) // Prints 8
Functions are a fundamental building block in Swift. By bundling code, accepting inputs, and returning outputs, they make your programs more powerful and organized. Now, let's test what you've learned.
What is the primary keyword used to declare a function in Swift?
Consider the following code:
func greet(person: String) {
print("Hello, \(person)!")
}
In this function definition, person: String is known as a...