Swift
Beginner
1 min read
Function Basics and Labels
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))