OneBite.Dev - Coding blog in a bite size

Declare A Void Function Without Return Value In Swift

Code snippet for how to Declare A Void Function Without Return Value In Swift with sample and detail explanation

Swift programming language is widely used for iOS and MacOS applications. One important concept in Swift, similar to many other programming languages, is the use of functions. Functions can be either with a “return value” or with “no return value”, which we often refer to as ‘void functions’.

Code snippet for Declaring a Void Function in Swift

func greetUser() {
    print("Hello, user")
}
greetUser()

Code Explanation for Declaring a Void Function in Swift

In the given code snippet, we are declaring a void function in Swift that does not return a value; instead, it performs a specific task.

func greetUser(): Here, we are defining the function using the static keyword func followed by the name of the function greetUser.

’()’ is used to define a list of parameters. In our case, we do not need any parameters, therefore it has been left blank.

The code block between the braces {...} is the body of the function. The logic of the function should be written within this block. In this function, print("Hello, user") is the operation performed by the function.

After defining the function, we are calling it by its name followed by two parentheses: greetUser(). This triggers the function to execute its logic, which in this case is to print “Hello, user” to the console.

Remember that if a function in Swift doesn’t return a value, it’s equivalent to returning void. Void functions in Swift are useful whenever you want to carry out tasks that do not need to send back data. In the example above, the function greetUser() performs an action (printing out a greeting) but does not need to communicate any information back to the part of the program that called it. Hence, declaring a void function is an appropriate approach.

swift