Swift by Example: Functions
Master Swift function syntax with this sample code demonstrating parameter declarations, return types, argument labels for readable function calls, omitting labels with underscore, and returning multiple values using tuples.
Code
// Basic function
func greet(person: String) -> String {
return "Hello, " + person + "!"
}
print(greet(person: "Anna"))
// Function with argument labels
func sayHello(to name: String, from sender: String) {
print("Hello (name), from (sender)")
}
sayHello(to: "Bob", from: "Alice")
// Omitting argument labels
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
let sum = add(5, 3)
// Multiple return values (Tuple)
func getMinMax(array: [Int]) -> (min: Int, max: Int)? {
if array.isEmpty { return nil }
return (array.min()!, array.max()!)
}Explanation
Functions are defined with the func keyword. You specify the parameter names, types, and the return type (using ->). If a function doesn't return a value, the return arrow and type can be omitted.
Swift functions use argument labels to make function calls read like sentences. By default, the parameter name is used as the label. You can provide a custom argument label before the parameter name (e.g., func sayHello(to name: String)), or use an underscore _ to omit the label entirely in the function call.
Functions can return multiple values using tuples. This is useful for returning related pieces of data, like a min and max value from an array. The return type can also be optional (e.g., (Int, Int)?) to handle cases where a valid return value cannot be produced.
Code Breakdown
func greet(person: String) -> String defines function signature with parameter and return type.to name: String defines 'to' as the external label and 'name' as the internal variable._ a: Int allows calling the function as add(5, 3) without labels.(min: Int, max: Int)? returns an optional tuple with named elements.
