Understanding Swift Return Statement
Understanding Swift Return Statement
In Swift, the return statement is used to exit from a function and optionally provide a value back to the caller. It plays a crucial role in controlling the flow of execution and ensuring functions produce the expected results.
A function in Swift can either return a value or return nothing
(denoted by Void
or simply omitting the return type).
When a function has a return type, using return
becomes
mandatory to provide the expected result.
Key Points to Remember
-
The
return
statement immediately exits the function and transfers control back to the caller. - If a function specifies a return type, it must return a value of that type.
-
A function with a
Void
return type can omit thereturn
statement or use it alone to exit early. -
Multiple
return
statements can be used in conditional branches within a function.
Syntax
func functionName(parameters)
-> ReturnType {
return value
}
If the function has no return type:
func functionName(parameters) {
return
// Optional in Void functions
}
Example 1: Returning a String Value
Let's demonstrate how a function can return a string in Swift.
import
Foundation
func
greet(name:
String) ->
String {
return
"Hello, \(name)!"
}
let message =
greet(name:
"Alice")
print(message)
Output
Example 2: Returning an Integer Value
import
Foundation
func square(of
number: Int)
-> Int {
return number * number
}
let result =
square(of: 5)
print("Square: \(result)")
Output
Example 3: Early Return in a Function
You can use the return
statement to exit a function
early based on a condition.
import
Foundation
func
checkEvenOrOdd(_ number:
Int) ->
String {
if number % 2 ==
0 {
return "Even"
}
return "Odd"
}
print(checkEvenOrOdd(7))