Defining and Calling Functions
1 | func greet(person: String) -> String { |
Function Parameters and Return Values
Functions Without Parameters
1 | func sayHelloWorld() -> String { |
Functions With Multiple Parameters
1 | func greet(person: String, alreadyGreeted: Bool) -> String { |
Functions Without Return Values
Functions without a defined return type return a special value of type Void. This is simply an empty tuple, which is written as ().
1 | func greet(person: String) { |
The return value of a function can be ignored when it is called:
1 | func printAndCount(string: String) -> Int { |
Functions with Multiple Return Values
1 | func minMax(array: [Int]) -> (min: Int, max: Int) { |
Optional Tuple Return Types
An optional tuple type such as (Int, Int)? is different from a tuple that contains optional types such as (Int?, Int?). With an optional tuple type, the entire tuple is optional, not just each individual value within the tuple.
1 | func minMax(array: [Int]) -> (min: Int, max: Int)? { |
Function Argument Labels and Parameter Names
- Each function parameter has both an argument label and a parameter name.
- By default, parameters use their parameter name as their argument label.
1 | func someFunction(firstParameterName: Int, secondParameterName: Int) { |
Specifying Argument Labels
1 | func greet(person: String, from hometown: String) -> String { |
Omitting Argument Labels
1 | func someFunction(_ firstParameterName: Int, secondParameterName: Int) { |
Default Parameter Values
If a default value is defined, you can omit that parameter when calling the function.
1 | func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) { |
Variadic Parameters
- A function may have at most one variadic parameter.
- The values passed to a variadic parameter are made available within the function’s body as an array of the appropriate type
1 | func arithmeticMean(_ numbers: Double...) -> Double { |
In-Out Parameters
- Function parameters are constants by default
- In-out parameters cannot have default values, and variadic parameters cannot be marked as inout.
- You can only pass a variable as the argument for an in-out parameter.
- You place an ampersand (&) directly before a variable’s name when you pass it as an argument to an in-out parameter, to indicate that it can be modified by the function.
1 | func swapTwoInts(_ a: inout Int, _ b: inout Int) { |
Function Types
1 | // The type of both of these functions is (Int, Int) -> Int |
Using Function Types
1 | func addTwoInts(_ a: Int, _ b: Int) -> Int { |
Function Types as Parameter Types
1 | func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { |
Function Types as Return Types
1 | func stepForward(_ input: Int) -> Int { |
Nested Functions
1 | func chooseStepFunction(backward: Bool) -> (Int) -> Int { |