Functions
Swift functions get external + internal names, default values, variadics, throws, and trailing closures. Together they make APIs read like a sentence.
Real Swift function signatures
EXAMPLE
// 1) Argument labels — external label optional with _
func greet(_ name: String, withPrefix prefix: String = "Hi") -> String {
"\(prefix), \(name)"
}
greet("Ada") // 'Hi, Ada'
greet("Bo", withPrefix: "Hello") // 'Hello, Bo'
// 2) Variadic args
func total(_ values: Int...) -> Int {
values.reduce(0, +)
}
total(1, 2, 3, 4) // 10
// 3) Multiple returns via tuple
func bounds(_ xs: [Int]) -> (min: Int, max: Int)? {
guard let first = xs.first else { return nil }
return xs.reduce((first, first)) { (acc, x) in
(Swift.min(acc.0, x), Swift.max(acc.1, x))
}
}
if let b = bounds([5, 1, 7, 3]) {
print(b.min, b.max) // 1 7
}
// 4) inout — pass by reference
func shift(_ x: inout Int, by delta: Int) {
x += delta
}
var count = 0
shift(&count, by: 5)
print(count) // 5
// 5) throws — typed errors
enum ParseError: Error { case empty, invalid }
func parsePositive(_ s: String) throws -> Int {
guard !s.isEmpty else { throw ParseError.empty }
guard let n = Int(s), n > 0 else { throw ParseError.invalid }
return n
}
do {
let n = try parsePositive("42")
} catch ParseError.invalid {
/* … */
}
// 6) Closures + trailing-closure syntax
let nums = [1, 2, 3, 4, 5]
let doubled = nums.map { \$0 * 2 }
let filtered = nums.filter { n in n.isMultiple(of: 2) }
let sum = nums.reduce(0, +)
// 7) @escaping closure params
func fetch(_ url: URL, then: @escaping (Data) -> Void) {
URLSession.shared.dataTask(with: url) { data, _, _ in
guard let data else { return }
then(data)
}.resume()
}
Why it matters
Trailing-closure syntax + meaningful argument labels are why Swift APIs read so well. When you design a function, choose labels that complete the sentence at the call site.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
func add(_ a: Int, _ b: Int) -> Int { a + b }
func divmod(_ a: Int, _ b: Int) -> (Int, Int) { (a/b, a%b) }
let (q, r) = divmod(17, 5)
Try it Yourself »
Discussion
Loading…