Function parameters receive values from the call site and let one function work with different inputs.

Pass values into a function

price
function_parameters.swift
Replay: real traced execution (multi-file project)
func addTax(price: Int, tax: Int) -> Int {
    return price + tax
}

let price = 20
let tax = 3
let total = addTax(price: price, tax: tax)

print("price=\(price)")
print("total=\(total)")
func addTax(price: Int, tax: Int) -> Int {
    return price + tax
}

let price = 12
let tax = 3
let total = addTax(price: price, tax: tax)

print("price=\(price)")
print("total=\(total)")
func addTax(price: Int, tax: Int) -> Int {
    return price + tax
}

let price = 35
let tax = 3
let total = addTax(price: price, tax: tax)

print("price=\(price)")
print("total=\(total)")
  1. price ← 20, tax ← 3

    5let price→ 20 = 20  //@price=12, 356let tax→ 3 = 37let total = addTax(price: price20, tax: tax3)
  2. func addTax(price: Int, tax: Int) -> Int

    1func addTax(price20: Int, tax3: Int) -> Int {2    return price20 + tax33}
  3. total ← 23

    6let tax = 37let total→ 23 = addTax(price: price20, tax: tax3)89print("price=\(price20)")10print("total=\(total23)")
    outputprice=20
    total=23
  1. price ← 12, tax ← 3

    5let price→ 12 = 126let tax→ 3 = 37let total = addTax(price: price12, tax: tax3)
  2. func addTax(price: Int, tax: Int) -> Int

    1func addTax(price12: Int, tax3: Int) -> Int {2    return price12 + tax33}
  3. total ← 15

    6let tax = 37let total→ 15 = addTax(price: price12, tax: tax3)89print("price=\(price12)")10print("total=\(total15)")
    outputprice=12
    total=15
  1. price ← 35, tax ← 3

    5let price→ 35 = 356let tax→ 3 = 37let total = addTax(price: price35, tax: tax3)
  2. func addTax(price: Int, tax: Int) -> Int

    1func addTax(price35: Int, tax3: Int) -> Int {2    return price35 + tax33}
  3. total ← 38

    6let tax = 37let total→ 38 = addTax(price: price35, tax: tax3)89print("price=\(price35)")10print("total=\(total38)")
    outputprice=35
    total=38

Follow the Parameters

  1. price starts as 20.
  2. The call is addTax(price: price, tax: 3).
  3. Inside the function, tax adds 3 to the price.
  4. total becomes 23.
  5. The program prints price=20 and total=23. | price | tax | total | | --- | --- | --- | | 20 | 3 | 23 | | 12 | 3 | 15 | | 35 | 3 | 38 |
parameters Parameters are local names inside the function body. Each call supplies the actual values used for that run.

Exercise: function_parameters.swift

Reproduce price=20 and total=23, then use the pinned price variants 12 and 35 to predict totals 15 and 38.