Swift: Defining a Function

Defining a Function in Swift:

We can define a function by mentioning its name , data type of return value and input values if any. A code block or body follows the definition and contains the function’s task in Swift.

Here’s how it works:

func functionName() -> returnType {
 // body of function

  • The keyword func denotes the start of a function. It follows by a camelCase-format name that describes the function’s objective. It’s best to give your functions a name that’s both descriptive and concise.
  • A pair of ( ) follows the functionName and can hold optional input values known as parameters. (Parameters will be discus further in the lesson!)
  • A return arrow (->) follows the parentheses, indicating the data type of return value. One of the following two syntaxes can use if a function does not return a value:
    1func functionName() { where the -> and type are completely omitted
    2func functionName() -> Void { where the type is listed as Void.
  • Finally, the returnType is followed by a code block that contains the function’s task code.

We’ll create a simple function without a return statement or parameters using the pseudocode above as a guide. We’ll learn more about these different parts and concepts as we progress through this lesson.

Here’s an example of a function that welcomes a user:

func welcoming() -> Void {
  print("How are things going for you today?");

The function’s name and a pair of parentheses can be used to refer to it: welcoming(). Because its body only contains two print statements and does not return any values, as indicated by the keyword Void. So, the welcoming() function can now use every time we want to greet a user.

Note: When you paste this code into the editor and hit “Run,” you’ll get an empty output terminal. The print() statements within it will be execute because our function hasn’t been called. In the next exercise, we’ll go over this in more detail; for now, let’s practice defining a function.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: