What if you could write a task once and use it everywhere without copying it?
Why Functions and closures in iOS Swift? - Purpose & Use Cases
Imagine you want to repeat a task many times in your app, like showing a greeting message in different places. Without functions, you'd have to write the same code again and again, which is tiring and confusing.
Writing the same code multiple times makes your app bigger and harder to fix. If you want to change the greeting, you must find and update every copy. This wastes time and can cause mistakes.
Functions let you write a task once and use it anywhere by calling its name. Closures are like mini-functions you can create on the spot, making your code neat and flexible.
print("Hello, User!") print("Hello, User!") print("Hello, User!")
func greet() {
print("Hello, User!")
}
greet()
greet()
greet()Functions and closures let you build apps that are easier to read, fix, and grow with less effort.
In a weather app, you can write a function to format temperature once, then use it everywhere to show consistent info without repeating code.
Functions save you from repeating code.
Closures let you create quick, reusable code blocks.
Both make your app cleaner and easier to manage.
Practice
func greet() { print("Hello") }Solution
Step 1: Understand closure definition
A closure is a block of code without a name that can be saved and used later.Step 2: Compare with function
Functions have names, closures do not but both can be reused.Final Answer:
An unnamed block of code that can be stored and passed around -> Option AQuick Check:
Closure = unnamed reusable code block [OK]
- Confusing closures with variables
- Thinking closures must have names
- Mixing closures with loops
Solution
Step 1: Identify closure syntax
Closures use curly braces with parameters and return type before 'in'.Step 2: Check each option
'let closure = { () -> Int in return 5 }' matches closure syntax. 'func closure() -> Int { return 5 }' declares a named function. 'let closure = func() -> Int { return 5 }' uses invalid syntax. 'let closure = (Int) -> { return 5 }' lacks 'in' keyword and has wrong parameter placement.Final Answer:
let closure = { () -> Int in return 5 } -> Option BQuick Check:
Closure syntax = curly braces + 'in' [OK]
- Using func keyword inside closure
- Missing 'in' keyword
- Wrong parameter syntax
let multiply = { (a: Int, b: Int) -> Int in
return a * b
}
print(multiply(3, 4))Solution
Step 1: Understand closure parameters and return
The closure takes two Ints and returns their product.Step 2: Calculate multiply(3, 4)
3 * 4 equals 12, so print outputs 12.Final Answer:
12 -> Option CQuick Check:
3 times 4 = 12 [OK]
- Adding instead of multiplying
- Concatenating numbers as strings
- Syntax errors in closure call
let add = { (a: Int, b: Int) Int in
return a + b
}Solution
Step 1: Check closure signature syntax
Return type must be preceded by '->' in closure signature.Step 2: Identify missing arrow
Code has '(a: Int, b: Int) Int' but should be '(a: Int, b: Int) -> Int'.Final Answer:
Missing '->' before return type -> Option AQuick Check:
Closure return type needs '->' [OK]
- Omitting '->' in closure signature
- Placing 'in' incorrectly
- Removing parameter types
sorted(by:) method?Solution
Step 1: Understand sorted(by:) closure
It expects a closure that returns true if first element should come before second.Step 2: Check each option
'let sortedNames = names.sorted(by: { s1, s2 in s1 < s2 })' returns true when s1 < s2 (correct for ascending alphabetical order). The version with s1 > s2 sorts descending. The version with (s1, s2) -> s1 < s2 uses invalid syntax without braces or 'in'. The version with s1 + s2 returns String, not Bool.Final Answer:
let sortedNames = names.sorted(by: { s1, s2 in s1 < s2 }) -> Option DQuick Check:
sorted(by:) needs Bool-returning closure [OK]
- Returning wrong type from closure
- Using wrong comparison operator
- Incorrect closure syntax
Ready to prove it?
Pass the test and this pattern moves unknown
