OneBite.Dev - Coding blog in a bite size

Declare A Simple Function In Swift

Code snippet for how to Declare A Simple Function In Swift with sample and detail explanation

Functions are the building blocks in any programming language and they are very important in Swift programming. This article will guide you through the steps on how to declare a simple function in Swift programming language.

Declaring a Simple Function in Swift

Here is an example of a simple Swift function declaration:

func greet() {
    print("Hello, World!")
}

Then, to call the function, you simply need to do this:

greet()

Code Explanation for Declaring a Simple Function in Swift

Let’s take it step by step to understand how this simple function in Swift is declared and used:

  1. func: This keyword is used to define a function.

  2. greet(): This is the name of the function. The empty brackets indicate that the function does not take any parameters. Swift’s syntax gives you the freedom to name the function anything you want, but it’s always a good practice to give it a name that represents its purpose.

  3. {}: These are the function body brackets. Any code that is written between these brackets is the code that will be executed when this function is called.

  4. print("Hello, World!"): This is a command that gets executed when greet() function is called. print() is a built-in Swift function that outputs text to the console. In this case, it outputs the string “Hello, World!“.

  5. greet(): This line of code at the bottom is a function call. This is how you instruct Swift to execute the code inside greet() function. Every time this function call appears in your code, it will execute the command to print “Hello, World!“.

In summary, declaring a simple function in Swift begins with the keyword ‘func’ followed by your chosen function name with parentheses and then a set of braces enclosing your function body which is the list of commands you want to be executed when the function is called.

swift