Line At A Time
Lesson 24: Return Values
Return Values Get an answer back from a function.
1func add(a: Int, b: Int) -> Int {
2 return a + b
3}
4
5print(add(a: 2, b: 3))
6print(add(a: 10, b: 20))
Terminal
$ swift main.swift
5
30
Every line, explained
func add(a: Int, b: Int) -> Int {
func defines a function: your own named block of code. Defining it does nothing on its own; it waits until somebody calls it. In a Swift script, define a function before the line that calls it. The arrow -> Int says this function hands back an Int. Read the whole line as: "a function add that takes two Ints and returns an Int".
return a + b
return hands the value back to whoever called the function, and the function ends.
}
This } closes the function.
print(add(a: 2, b: 3))
add(a: 2, b: 3) runs the function and becomes its returned value: 5. Then print shows it.
print(add(a: 10, b: 20))
Same function, different inputs, different answer: 30.