Lesson 32Functions
Parameters
Function Parameters
Parameters let you pass data into functions. Swift has unique features for making function calls readable and flexible!
Parameter Types
Basic Parameter
func f(name: String)Call: f(name: "value")
No External Label
func f(_ name: String)Call: f("value")
Custom Label
func f(for name: String)Call: f(for: "value")
Variadic
func f(_ nums: Int...)Call: f(1, 2, 3, 4)
inout Parameters
Use inout when you need to modify the original value. Remember to use & when calling!
Making Code Readable
Swift encourages readable function calls:
move(from: 0, to: 100)Reads like English: "move from 0 to 100"
main.swift
// BASIC PARAMETERS
func greet(name: String) {
print("Hello, \(name)!")
}
greet(name: "Alice") // name is required
// MULTIPLE PARAMETERS
func describe(name: String, age: Int, hobby: String) {
print("\(name) is \(age) and loves \(hobby)")
}
describe(name: "Bob", age: 13, hobby: "coding")
// PARAMETER ORDER MATTERS!
// Must provide arguments in the same order as defined
// EXTERNAL AND INTERNAL NAMES
// Swift lets you have two names for each parameter
func greet(person name: String) {
// 'person' is external (used when calling)
// 'name' is internal (used inside function)
print("Hello, \(name)!")
}
greet(person: "Charlie")
// OMITTING EXTERNAL NAME WITH _
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
print(add(5, 3)) // No labels needed!
// DIFFERENT EXTERNAL AND INTERNAL NAMES
func move(from start: Int, to end: Int) {
print("Moving from \(start) to \(end)")
}
move(from: 0, to: 100) // Reads like English!
// INOUT PARAMETERS (modifies original value)
func double(_ number: inout Int) {
number *= 2
}
var myNumber = 5
double(&myNumber) // Note the & symbol
print(myNumber) // 10 (original changed!)
// VARIADIC PARAMETERS (accepts any number of values)
func sum(_ numbers: Int...) -> Int {
var total = 0
for num in numbers {
total += num
}
return total
}
print(sum(1, 2, 3)) // 6
print(sum(1, 2, 3, 4, 5)) // 15Try It Yourself!
Create a function `sendEmail(to recipient: String, with message: String)` that prints a formatted email. Make it read naturally!