Ad space (banner)
๐ŸฆSwift Lessons
Lesson 6 / 68

Writing a Function

In this lesson you will learn the basic way to define a function in Swift so you can reuse the same logic over and over. This is for anyone searching for "Swift functions how to use".

You define a function with func name(label: Type) -> ReturnType. Argument labels are what make a Swift function call read almost like natural English.

The sample code has greet take a name: String argument and return a greeting, with the return type stated explicitly as -> String. Writing the return type with -> makes the intent of the code much clearer.

A common stumbling block for beginners is the difference between the argument label and the internal parameter name. At the call site you write the label, as in greet(name: "Bob"), but the label does not have to match the name used inside the function.

In real-world development, gathering shared logic into functions reduces duplication and means a fix only has to be made in one place.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)