FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

< Back to Latest Articles

Creating a custom property wrapper using DynamicProperty

It’s not hard to make a basic property wrapper, but if you want one that automatically updates the body property like @State you need to do some extra work. In this article I’ll show you exactly how it’s done, as we build a property wrapper capable of reading and writing documents from our app’s container.

Watch the video here, or read the article below

Quick links

Reading and writing

We’re going to approach this property wrapper in two passes: a first pass able to read and write values, and a second pass that’s able to project a binding as well.

First, the easy part: we’re going to create a new property wrapper struct called Document that will store its value as a string, and also a URL pointing to the file it’s modifying. Because we’ll want to modify the text value over time, we’ll mark with the @State property wrapper so SwiftUI will look after it for us.

Start with this:

@propertyWrapper struct Document {
    @State private var value = ""
    private let url: URL
}

In order to be a valid property wrapper, our Document struct needs to have a wrappedValue property that stores the actual value we’re working with. In our case we already have that in value, but we made that private for a reason: when we interact with this property wrapper we want to add some extra work so that our new value gets written to disk automatically.

So, our wrappedValue property will be computed: when we’re reading it we’ll just send back value, but when we’re writing we’ll save it to wherever our file URL is then update value.

Now, we need a little bit of SwiftUI magic here, because if we have a setter for wrappedValue then we’ll be modifying the struct we’re inside and that will cause problems. Fortunately, we’re not actually changing the Document struct: we’re using @State, so we’re bypassing the struct entirely and having SwiftUI store the value. So, rather than making a regular setter, we can instead make a nonmutating setter, because our underlying struct won’t actually be changing.

Add this property to Document now:

var wrappedValue: String {
    get {
        value
    }
    nonmutating set {
        do {
            try newValue.write(to: url, atomically: true, encoding: .utf8)
            value = newValue
        } catch {
            print("Failed to write output")
        }
    }
}

And now we just need an initializer that provides initial values for both url and the value state. The first of these we can figure out by using FileManager to append the user’s filename to the app’s documents directory, but for the latter we need to load the initial value of the text file and wrap that in a State object.

Here’s that in code:

init(_ filename: String) {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    url = paths[0].appendingPathComponent(filename)

    let initialText = (try? String(contentsOf: url)) ?? ""
    _value = State(wrappedValue: initialText)
}

That’s it – that’s our first pass of the property wrapper complete. To try it we need to update ContentView to use the @Document property wrapper and place its context inside a text view, but in order to make the test interesting we’re also going to add a button to simulate changing its value – this will just generate a random number and place it into the document.

Here’s the new ContentView:

struct ContentView: View {
    @Document("test.txt") var document

    var body: some View {
        NavigationView {
            VStack {
                Text(document)

                Button("Change document") {
                    document = String(Int.random(in: 1...1000))
                }
            }
            .navigationTitle("SimpleText")
        }
    }
}

If you run that now you’ll see the text view is empty by default, and if you press the button nothing will happen. Yes, after all that work we don’t actually have much to show, but that’s okay: with one tiny change we can bring the whole thing to life.

You see, right now SwiftUI doesn’t realize it should be watching our property wrapper for change notification, even though it has an @State property inside there. To fix this we need to make Document conform to the DynamicProperty protocol, like this:

@propertyWrapper struct Document: DynamicProperty {

In fact, that’s all we need to do – SwiftUI will take care of the rest for us. Go ahead and run the app again, because if you press the button it will update automatically. Even better, the new contents have been written to “test.txt” automatically, so if you relaunch the app you’ll see it remembers its last value – nice!

Projecting values

Wrapping a simple string works great for simple property wrappers like we have right now, but for more advanced purposes you’re also likely to want to expose a projected value. This allows us to create an alternative way of using the property we’re wrapping, and it’s down to us to define exactly what it does.

SwiftUI’s own @State property wrapper uses the projected value to create a binding for its data, and if we do the same thing here then it would allow us to bind directly to a document so that every change we make gets saved out.

This takes remarkably little code to accomplish. First we need to add a new property to Document that declares our projected value and how it works. Projected values must always be called projectedValue, but otherwise can work however you want.

So, start by adding this property to Document:

var projectedValue: Binding<String> {
    Binding(
        get: { wrappedValue },
        set: { wrappedValue = $0 }
    )
}

It’s worth stopping to step through what that code does: when our binding is written to we update wrappedValue, which in turn triggers our nonmutating setter, which is what causes the new value to be written to disk.

And now we can update ContentView to bind a TextEditor directly to our document, like this:

TextEditor(text: $document)

If you run that back you’ll see every change you make is immediately saved, and will also be restored when you relaunch the app. Nice!

Challenges

If you want to take this tutorial further, here are some suggestions:

  1. Rather than have our binding write to disk every time a single character is changed, can you write code that simply sets a dirty flag and handle the writing at a later date? This might be periodically using Timer, or perhaps even by detecting the app moving to the background.
  2. Can you think of a way for our property wrapper to detect external changes, and reload itself in that case? For example, if someone else modifies the file, our wrapper should detect that and load the modified file. This might be as simple as a timer checking when the file was last modified.

If you liked this, you'd love Hacking with Swift+…

Here's just a sample of the other tutorials, with each one coming as an article to read and as a 4K Ultra HD video.

Find out more and subscribe here


Ultimate Portfolio App: Introduction

14:17

ULTIMATE PORTFOLIO APP

FREE: Ultimate Portfolio App: Introduction

While I’m sure you’re keen to get started programming immediately, please give me a few minutes to outline the goals of this course and explain why it’s different from other courses I’ve written.

Functional programming in Swift: Introduction

6:52

FUNCTIONAL PROGRAMMING

FREE: Functional programming in Swift: Introduction

Before you dive in to the first article in this course, I want to give you a brief overview of our goals, how the content is structured, as well as a rough idea of what you can expect to find.

How to use phantom types in Swift

24:11

ADVANCED SWIFT

FREE: How to use phantom types in Swift

Phantom types are a powerful way to give the Swift compiler extra information about our code so that it can stop us from making mistakes. In this article I’m going to explain how they work and why you’d want them, as well as providing lots of hands-on examples you can try.

Trees

31:55

DATA STRUCTURES

FREE: Trees

Trees are an extraordinarily simple, extraordinarily useful data type, and in this article we’ll make a complete tree data type using Swift in just a few minutes. But rather than just stop there, we’re going to do something quite beautiful that I hope will blow your mind while teaching you something useful.

Making the most of optionals

23:07

ADVANCED SWIFT

FREE: Making the most of optionals

Swift’s optionals are implemented as simple enums, with just a little compiler magic sprinkled around as syntactic sugar. However, they do much more than people realize, and in this article I’m going to demonstrate some of their power features that can really help you write better code – and blow your mind along the way.

User-friendly network access

14:26

NETWORKING

FREE: User-friendly network access

Anyone can write Swift code to fetch network data, but much harder is knowing how to write code to do it respectfully. In this article we’ll look at building a considerate network stack, taking into account the user’s connection, preferences, and more.

Understanding generics – part 1

20:01

INTERMEDIATE SWIFT

FREE: Understanding generics – part 1

Generics are one of the most powerful features of Swift, allowing us to write code once and reuse it in many ways. In this article we’ll explore how they work, why adding constraints actually helps us write more code, and how generics help solve one of the biggest problems in Swift.

Making your app accessible

33:12

ULTIMATE PORTFOLIO APP

FREE: Making your app accessible

It is my firm belief that every iOS app should be usable to everyone, and putting in the work to make your app function well no matter who is using it says a lot about the kind of developer you are.

Shadows and glows

19:50

SWIFTUI SPECIAL EFFECTS

FREE: Shadows and glows

SwiftUI gives us a modifier to make simple shadows, but if you want something more advanced such as inner shadows or glows, you need to do extra work. In this article I’ll show you how to get both those effects and more in a customizable, flexible way.

Using memoization to speed up slow functions

36:18

HIGH-PERFORMANCE APPS

FREE: Using memoization to speed up slow functions

In this article you’ll learn how memoization can dramatically boost the performance of slow functions, and how easy Swift makes it thanks to its generics and closures.

Creating a WaveView to draw smooth waveforms

32:08

CUSTOM SWIFTUI COMPONENTS

FREE: Creating a WaveView to draw smooth waveforms

In this article I’m going to walk you through building a WaveView with SwiftUI, allowing us to create beautiful waveform-like effects to bring your user interface to life.

Building a RadialMenu that shows many buttons around it

32:13

CUSTOM SWIFTUI COMPONENTS

Building a RadialMenu that shows many buttons around it

Sometimes pressing a button needs to present more buttons, and although you can use an action sheet for this it’s not ideal because it appears in a different location. In this article I’ll show you how to build a radial menu, which solves the problem by presenting a ring of buttons close to the user’s touch.

First steps in UI

18:01

ULTIMATE PORTFOLIO APP

First steps in UI

Now that we have our basic data model configured and coded, we can put it to use by building a simple user interface to help make sure our data is in place and working correctly.

UIKit updates: UICollectionView lists

1:26:39

HACKING WITH SWIFT LIVE 2020

UIKit updates: UICollectionView lists

In this part we’re going to build an app to explore SF Symbols, all built using the massive new updates to UICollectionView that let it act like a table view.

Offering in-app purchases, part 1

51:56

ULTIMATE PORTFOLIO APP

Offering in-app purchases, part 1

Although many apps work great when paid for up front, many more work better when using a freemium model – you get lots of downloads of a free app, then charge for some kind of premium service. In this article we’re going to prepare to limit our app unless the user has paid for an unlock, but we’ll be using a flexible approach you can adapt easily.

Remaking the Tips app

27:45

REMAKING APPS

Remaking the Tips app

In this article we’re going to look at how to rebuild the Tips app using SwiftUI, including how to make scrolling tabs of content, how to get a parallax scrolling effect, and more.

Using maps in SwiftUI

1:06:58

HACKING WITH SWIFT LIVE 2020

Using maps in SwiftUI

We’re going to look at integrating MapKit into SwiftUI, but first I want you to try integrating your new knowledge of lazy stacks into a real iOS app.

Querying data from iCloud

34:39

ULTIMATE PORTFOLIO APP

Querying data from iCloud

In the previous step we added the ability to upload projects and items to iCloud, then used the iCloud Dashboard to check the data had arrived safely. In this step we’re going to load shared projects, and let users browse them.

The pros and cons of operator overloading

23:37

ADVANCED SWIFT

The pros and cons of operator overloading

I’ve written about operator overloading previously, not least in my book Pro Swift, but in the article I want to go into more depth on the places where it’s really useful – and the places where it’s not such a good idea.

Remaking the welcome screen

22:31

REMAKING APPS

Remaking the welcome screen

Few things in SwiftUI are quite so easy and yet quite so rewarding as rebuilding Apple’s welcome screens. In this article we’ll do just that, making it flexible enough to adapt easily for your own apps.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.