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

How to simulate instance variables with an extension

Why adding your own userInfo dictionary can be helpful

Paul Hudson       @twostraws

Developers for Apple’s platforms will already be familiar with the userInfo dictionary: it’s used in push messages, user activities, 3D Touch quick actions, notification center, timers, and many other places – it’s an extremely common pattern.

Using a dictionary like this allows Apple to add new data over time without worrying so much about source compatibility; they can add or rename new things freely, and the dictionary will just adapt as needed. Of course, the downside is that dictionaries often use strings for keys, which are inefficient and error-prone - there’s a reason Apple provides typedefs for values, using keys like UIApplicationLaunchOptionsKey.shortcutItem rather than plain strings.

This technique can be applied in our own code so that associative storage can simulate adding properties in a type. You see, although Swift’s extensions let you add methods and computed properties to existing data types, they don’t let you add stored properties. This stops you from arbitrarily changing the layout of existing data types, but can also lead to situations where you need to create a subclass in order to add new storage – which in turn gives you all the tight coupling that class inheritance brings.

Associative storage, where available, can serve as an excellent middle ground: you can read and write custom data in the storage as if it were stored properties, without needing to modify the structure of the data type itself.

My favorite of this comes from the Kitura server-side Swift framework: they have a RouterRequest class that signifies a user requesting a web resource, and that class has a userInfo property to store arbitrary data. Rather than have developers dig around in userInfo they created an extension to RouterRequest that provides a computed property with getters and setters that work with userInfo on their behalf.

To demonstrate this functionality, we can write some playground that adds virtual stored properties to an existing data type. Create a new playground and give it this content:

struct Request {
    var route: String
    var time: Date
    var userInfo: [String: Any]

    init(route: String, time: Date) {
        self.route = route
        self.time = time
        userInfo = [:]
    }
}

That models a simple web request coming into a server – the route is the page they requested, and the time is the current system time.

Notice the userInfo dictionary – that’s key to this whole operation. I added a custom initializer because we don’t want to worry about the existence of userInfo when the structs are being created.

If a type was created by someone else and you wanted to add new stored properties to it, the only option would usually be to subclass it if you could. However, when they add a userInfo dictionary another option is possible: we can write an extension that adds a computed property to dip into that dictionary.

Our Request struct has no place to store cookies being sent by the browser, so we can use the userInfo dictionary to add that in a type-safe way.

Add this extension to your playground:

extension Request {
    private var cookiesKey: String { return "@COOKIES@" }

    var cookies: [String: String] {
        get {
            return userInfo[cookiesKey] as? [String: String] ?? [:]
        }

        set {
            userInfo[cookiesKey] = newValue
        }
    }
}

That defines a custom cookiesKey property that we can use inside both the setter and getter, giving it a string purposefully designed to be weird so that it won’t clash with any other values being placed in the userInfo dictionary.

It also defines a cookies computed property. Internally we can see that this stores its data in the userInfo dictionary, but all users externally see is a regular cookies dictionary property just like any other dictionary.

So, we can use our new property immediately:

var request = Request(route: "/login", time: Date())
request.cookies = ["username": "twostraws"]

From the perspective of our API users, they can now extend our type to add any data they want without having to constantly poke around in the murky world of dictionary keys – all it took was one extra property in our type.

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!

Where next?

This article has been adapted from a chapter in my book Swift Design Patterns. If you want to learn more about associative storage, delegation, selectors, and more – as well as learning why these things work the way they do – you should check out the book!

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!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.