UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to share structs using boxing

Sometimes it’s exactly what you need

Paul Hudson       @twostraws

Value types are everywhere in Swift: strings, integers, and are all value types. Arrays, dictionaries, and sets are value types. Structs, tuples, and enums – they are all value types too.

As a result, I’ve said many times before that I consider value types to be one of three components that make natural Swift, alongside functional programming and protocol-oriented programming. (And if you didn’t already know that, click here to download a free video explaining the benefits these three provide!)

So, hopefully by now you’re already using structs where possible, because their unique ownership model makes your code easier to reason about, easier to test, and easier to debug. However, as your application grows, you might find your situation becomes less black and white: your app might work 95% of the time with structs, but maybe once or twice everything would have been a whole lot easier if you had a class instead because you can share data when it’s truly needed.

All is not lost: bearing in mind that I strongly believe you should prefer structs where possible, there is a way to share value types in several places if you’re convinced it’s the right solution. The technique is called boxing – not the punchy, sweaty sort of boxing, but as in “placing something inside a box.” This approach wraps a value type inside a reference type so you can share it more easily, and is commonly seen in languages such as C# and Java.

I want to walk you through a practical example so you can see for yourself how it works. First, here’s a User struct:

struct User {
    var name: String
    var age: Int
    var favoriteIceCream: String
}

let taylor = User(name: "Taylor Swift", age: 26, favoriteIceCream: "Chocolate")

Because structs are value types, if you attempt to assign that taylor value to multiple places each will get its own unique copy. This means one place can’t make a change and have that affect all other places.

However, if you wanted to share that taylor struct across multiple objects, you could wrap it inside a class and share that. In code, you’d create a UserBox class like this:

final class UserBox {
    var user: User

    init(user: User) {
        self.user = user
    }
}

let box = UserBox(user: taylor)

That is a class container around the User struct, and as a reference type will be shared rather than copied.

Finally, let’s create a TestContainer class that simulates some parts of your app, such as different view controllers:

final class TestContainer {
    var box: UserBox!
}

let container1 = TestContainer()
let container2 = TestContainer()

container1.box = box
container2.box = box

That creates two containers, each of which point at the same UserBox object, which in turn means they are pointing at the same User struct.

To prove this works, we could write code like this:

print(container1.box.user.name)
print(container2.box.user.name)

box.user.name = "Not Taylor"

print(container1.box.user.name)
print(container2.box.user.name)

That will print “Taylor Swift” twice, then “Not Taylor” twice, proving that changing the value in one container changes the value in the other.

It’s undeniable that this approach weakens the power and safety of value types a little, but at least it makes explicit which situations give you the safety of value types and which don’t. By using boxes you’re stating “this bit is explicitly shared” rather than implicitly sharing everything, which is what you would have when using classes everywhere.

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Creating a generic box

If you intend to make extensive use of boxing and unboxing, you might want to consider creating a generic Box class like this:

final class Box<T> {
    var value: T

    init(value: T) {
        self.value = value
    }
}

final class TestContainer {
    var box: Box<User>!
}

That way you can share other types of structs without having to create lots of different box classes.

In the same way that it’s a good idea to make all your structs conform to Equatable, you might also want to use a conditional conformance to make Box equatable when its contents are equatable, like this:

extension Box: Equatable where T: Equatable {
    static func == (lhs: Box<T>, rhs: Box<T>) -> Bool {
        return lhs.value == rhs.value
    }
}

Where next?

If you’d like to learn more about value types, boxing, and other ways to help you write natural Swift code, you should read my book Pro Swift – it teaches a wide range of advanced techniques, and comes with over six hours of videos.

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.