NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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 own right – 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 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 Stream

SPONSORED Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.

Try now!

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

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.