WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

When should you use inout parameters?

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Swift’s inout parameters are very commonly used, but less commonly created. That is, they are the kind of thing you’ll rely on a lot, perhaps without even realizing, but it’s not common you’ll want to create functions with them – at least not while you’re learning.

How common are they? Well, all of Swift’s operators are actually implemented as functions behind the scenes – things like +, -, and so on. Yes, they really are just functions behind the scenes. You can imagine them a bit like this:

func +(leftNumber: Int, rightNumber: Int) -> Int {
    // code here

So, when writing 5 + 3 we’re actually calling a function called + takes an integer on the left (5) and an integer on the right (3), and returns a new integer containing the result.

Now think about the += operator, which both adds and assigns at the same time. That doesn’t have a return value, but actually modifies the original value directly. As a result, it looks a bit more like this:

func +=(leftNumber: inout Int, rightNumber: Int) {
    // code here

Broadly speaking, it’s best to avoid creating inout parameters until you feel confident they are definitely the right choice. When you’re learning (and actually when you’re very experienced too!) it’s usually better to send in some data to a function and get new data back, because it makes it easier to follow your program’s logic.

That doesn’t mean inout isn’t worth knowing, only that you want to be really sure you need it before you begin.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.7/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.