Skip to Content
Learn
Functions
Implicit Return

Swift version 5.1, released in February 2020, includes a newly supported feature for functions known as an implicit return. It exists in various other programming languages and aids in shortening the code within a function.

So far, we’ve used the return keyword in each one of our functions that expects a value returned. When there’s only a single expression or value in the body, we can use Swift’s implicit return feature, omitting the return keyword, and still return our value.

Take a look at the following function:

func findProduct(a: Int, b: Int) -> Int { return a * b }

findProduct(a:b:) accepts two Int parameters and returns their product in Int form. Since the function contains a single expression, we can practice implicitly returning the expression by removing the return keyword:

func findProduct(a: Int, b: Int) -> Int { a * b }

Both strategies will yield the same result when invoked:

print(findProduct(a: 4, b: 7)) // Prints: 28

Implicit returns are optional and solely used for shortening the code within a function body. They are not mandatory and are up to the developer’s stylistic preference.

Note: Both explicit and implicit returns are valid but keep in mind that implicit returns are only supported in Swift version 5.1 or later. Using an implicit return in earlier versions will elicit the following error:

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

Instructions

1.

In Remainder.swift, declare a function, findRemainder(), that will accept two Int parameters: dividend and divisor and return an Int type.

Within the function, return the arithmetic expression, dividend % divisor using the return keyword.

2.

Call the function and pass in 10 as the argument for dividend and 4 as the argument for divisor.

Wrap the function call in a print() statement to see the function’s output.

3.

Remove the return keyword from within the function body. Your function should still execute and return the correct remainder using implicit return.

Folder Icon

Take this course for free

Already have an account?