Line At A Time
Lesson 23: Argument Labels
Argument Labels Give a function information using Swift's readable labels.
1func greet(name: String) {
2 print("Hello, \(name)!")
3}
4
5greet(name: "Ada")
6greet(name: "Grace")
Terminal
$ swift main.swift
Hello, Ada!
Hello, Grace!
Every line, explained
func greet(name: String) {
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 parameter is name: String (its name, a colon, then its type). Swift is strict about types on parameters.
print("Hello, \(name)!")
Inside a Swift string, \(...) is magic: Swift swaps \(name) for the value of name. This is called string interpolation, and it is THE Swift way to mix variables into text. Inside the function, name holds whatever the caller passed in.
}
This } closes the function.
greet(name: "Ada")
Calling the function, you write the label too: greet(name: "Ada"). Swift calls read like little sentences on purpose; it is one of the language's favourite features.
greet(name: "Grace")
Same function, different input, different greeting.