Reading — step 1 of 5
Learn
~1 min readFunctions and Closures
Functions use func. Parameters have external labels and internal names. The external label is what callers write at the call site:
func greet(name: String, greeting: String = "Hello") -> String {
return "\(greeting), \(name)!"
}
print(greet(name: "Alice")) // Hello, Alice!
print(greet(name: "Bob", greeting: "Howdy")) // Howdy, Bob!
To omit the label at the call site, prefix with _:
func add(_ a: Int, _ b: Int) -> Int { a + b }
add(3, 4) // no labels
For single-expression functions, drop the return. The return type is -> Type after the params. Void (or nothing) means no return.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…