Swift: Implicit Return

Implicit Return in Swift:

An implicit return is a newly supported feature for functions in Swift version 5.1, which was released in February 2020. It can be found in a variety of programming languages and aids in the reduction of code within a function.

We’ve used the return keyword in every function that expects a value to be returned so far. When the body contains only a single expression or value, we can use Swift’s implicit return feature to return our value without using the return keyword.

Take a look at the function below:

func findSum(x: Int, y: Int) -> Int {
 return x + y ;
}

findSum(x:y:) takes two Int parameters and returns an Int value as the result. We can practise implicitly returning the expression by removing the return keyword because the function only has one expression:

func findSum(x: Int, y: Int) -> Int {
 x * y;
}

When both strategies are used, the same result is obtained:

print(findSum(x: 10, y: 4)); // Prints: 14

Note: Implicit returns are only used to shorten the code within the body of a function. They are not required and are left to the developer’s personal taste.

Both explicit and implicit returns are acceptable, but implicit returns are only supported in Swift 5.1 and later. In earlier versions, using an implicit return will result in the following error:

error: missing return in a function expected to return 'Int'

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: