AnyCompiler

Functions

A function is declared with func, a name, parameters in parentheses, and a return type after ->. Swift distinguishes a parameter's external label (how callers name it) from its internal name (how the function body refers to it); an underscore drops the external label entirely, which is why multiply(6, 7) below doesn't need multiply(a: 6, b: 7).

func multiply(_ a: Int, _ b: Int) -> Int {
    return a * b
}
print(multiply(6, 7))
Output
42

A parameter can also have a default value, letting callers omit it entirely when the default is what they want.

func greet(name: String, greeting: String = "Hello") -> String {
    return "\(greeting), \(name)!"
}
print(greet(name: "Swift"))
print(greet(name: "Swift", greeting: "Hi"))
Output
Hello, Swift!
Hi, Swift!

Next: optionals — the feature Swift is best known for, and what a real optionals compile error looks like.

Practice exercise

Write a function named multiply that takes two unnamed Int parameters and returns their product, then call multiply(6, 7) and print the result.