Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
When is the return keyword not needed in a Swift function? - a free tutorial

NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

When is the return keyword not needed in a Swift function?

Paul Hudson    @twostraws   

We use the return keyword to send back values from functions in Swift, but there is one specific case where it isn’t needed: when our function contains only a single expression.

Now, “expression” isn’t a word I use often, but it’s important to understand here. When we write programs we do things like this:

5 + 8

Or this:

greet("Paul")

These lines of code get resolved to a single value: 5 + 8 gets resolved to 13, and greet("Paul") might return a string “Hi, Paul!”

Even some longer code will get resolved to a single value. For example, if we had three Boolean constants like this:

let isAdmin = true 
let isOwner = false
let isEditingEnabled = false

Then this line of code would resolve to a single value:

isOwner == true && isEditingEnabled || isAdmin == true

That would become “true”, because even though isOwner is false, isAdmin is true, so the whole expression becomes true.

So, lots of code we write can be resolved to a single value. But there’s also a lot of code that can’t be resolved to a single value. For example, what’s the value here:

let name = "Otis"

Yes, that creates a constant, but it doesn’t become a value in its – we couldn’t write return let name = "Otis".

Similarly, we write conditions like this:

if name == "Maeve" {
    print("Hello, Maeve!")
}

That also can’t become a single value, because it has a condition in there.

Now, all this matters because these divisions have names: when we our code can be boiled down to a single value, such as true, false, “Hello”, or 19, we call that an expression. Expressions are things that can be assigned to a variable, or printed using print(). On the other hand, when we’re performing actions such as creating variables, starting a loop, or checking a condition, then we call that a statement.

All this matters because Swift lets us skip using the return keyword when we have only one expression in our function. So, these two functions do the same thing:

func doMath() -> Int {
    return 5 + 5
}

func doMoreMath() -> Int {
    5 + 5
}

Remember, the expression inside there can be as long as you want, but it can’t contain any statements – no loops, no conditions, no new variables, and so on.

Now, you might think this is pointless, and you would always use the return keyword. However, this functionality is used very commonly with SwiftUI, so it’s worth keeping in mind.

Before we’re done, I want to mention one more thing. You’ve seen how we can use operators such as +, &&, and || in our expressions, because they still resolve to a single value. Well, the ternary operator works here too, and in fact this is the primary use case for it: when you want to have a single expression, but don’t want to have a full if.

To demonstrate this, consider the following function:

func greet(name: String) -> String {
    if name == "Taylor Swift" {
        return "Oh wow!"
    } else {
        return "Hello, \(name)"
    }
}

If we wanted to remove the return statements in there, we could not write this:

func greet(name: String) -> String {
    if name == "Taylor Swift" {
        "Oh wow!"
    } else {
        "Hello, \(name)"
    }
}

That isn’t allowed, because we have actual statements in there – if and else.

However, we could use the ternary operator like this:

func greet(name: String) -> String {
    name == "Taylor Swift" ? "Oh wow!" : "Hello, \(name)"
}

That is a single expression. If name is equal to “Taylor Swift” then it will resolve something like this:

  • Swift will check whether name is Taylor Swift or not.
  • It is, so name == "Taylor Swift" is true.
  • The ternary operator will realize its condition is now true, so it will pick “Oh wow” rather than “Hello, (name)”.

So, when that function runs it effectively boils down to this:

func greet(name: String) -> String {
    "Oh wow!"
}

Letting us put conditional functionality into a single line of code is where the ternary operator really shines. And, because SwiftUI uses single expression functions quite a lot, this means ternary operators get used in SwiftUI quite a lot too.

Hacking with Swift is sponsored by Instabug

SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.

Start your free trial!

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Link copied to your pasteboard.