SyntaxStudy
Sign Up
Swift Function Basics and Labels
Swift Beginner 1 min read

Function Basics and Labels

Swift functions use argument labels and parameter names, giving call sites a natural English-language feel. The external label is used at the call site, while the internal name is used inside the function body. Using _ as the external label omits the label at the call site. Default parameter values reduce the number of overloads needed. Functions can return multiple values via tuples, and can return optionals to indicate possible failure.
Example
// Basic function
func greet(name: String) -> String {
    return "Hello, \(name)!"
}
print(greet(name: "Alice"))

// External label vs internal name
func move(from start: Int, to end: Int) -> Int {
    return end - start
}
let distance = move(from: 5, to: 10)

// Omit label with _
func add(_ a: Int, _ b: Int) -> Int { a + b }
let sum = add(3, 4)

// Default parameters
func createURL(scheme: String = "https", host: String, path: String = "/") -> String {
    return "\(scheme)://\(host)\(path)"
}
let url1 = createURL(host: "example.com")
let url2 = createURL(scheme: "http", host: "api.example.com", path: "/v1")

// Tuple return
func minMax(array: [Int]) -> (min: Int, max: Int)? {
    guard !array.isEmpty else { return nil }
    return (array.min()!, array.max()!)
}
if let bounds = minMax(array: [1, 5, 3, 9, 2]) {
    print("Min: \(bounds.min), Max: \(bounds.max)")
}

// Variadic parameters
func average(_ numbers: Double...) -> Double {
    numbers.reduce(0, +) / Double(numbers.count)
}
print(average(1, 2, 3, 4, 5))