Lesson 34Functions
Argument Labels
External vs Internal Names
Swift lets you use different names when calling a function vs inside the function. This makes your code more readable!
Label Patterns
Same Label
func f(name: String)f(name: "value")
Custom Label
func f(for name: String)f(for: "value")
No Label
func f(_ name: String)f("value")
Mixed
func f(_ a: Int, to b: Int)f(5, to: 10)
Common Prepositions
tofromatinwithbyfor
Best Practices
- Omit the first label if the function name explains it
- Use prepositions for clarity (to, from, at, in)
- Make function calls read like English sentences
- Be consistent within your codebase
main.swift
// ARGUMENT LABELS EXPLAINED
// Swift has TWO names for each parameter:
// 1. External name (used when calling)
// 2. Internal name (used inside function)
// DEFAULT: Same name for both
func greet(name: String) {
print("Hello, \(name)!") // 'name' used internally
}
greet(name: "Alice") // 'name' used externally
// CUSTOM EXTERNAL LABEL
func greet(person name: String) {
print("Hello, \(name)!") // 'name' is internal
}
greet(person: "Bob") // 'person' is external
// WHY USE DIFFERENT LABELS?
// Makes function calls read like English!
func send(message text: String, to recipient: String) {
print("Sending '\(text)' to \(recipient)")
}
send(message: "Hello!", to: "Charlie")
// Reads: "send message 'Hello!' to Charlie"
// OMITTING EXTERNAL LABEL WITH _
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
print(add(5, 3)) // No labels needed!
// Common pattern: first parameter without label
func contains(_ element: String, in array: [String]) -> Bool {
return array.contains(element)
}
contains("apple", in: ["apple", "banana"])
// MULTIPLE LABELS EXAMPLE
func move(from source: String, to destination: String) {
print("Moving from \(source) to \(destination)")
}
move(from: "Home", to: "School")
// MAKING API-LIKE FUNCTIONS
func setColor(red r: Int, green g: Int, blue b: Int) {
print("RGB(\(r), \(g), \(b))")
}
setColor(red: 255, green: 128, blue: 0)
// PREPOSITION PATTERN
func insert(_ item: String, at index: Int) {
print("Inserting \(item) at position \(index)")
}
insert("new item", at: 5)
// Best practices:
// 1. Omit label for first param if it's obvious
// 2. Use prepositions (to, from, at, in, with)
// 3. Make calls read like English sentencesTry It Yourself!
Create a function `copy(_ text: String, to clipboard: String)` that reads naturally when called!