Exploring Swift: Property wrappers in the wild
Property wrappers were introduced in Swift 5.1 as a way to make it easier to reuse common programming patterns, but since then they have grown to work with local context, function and closure parameters, and more. We’re lucky enough to have lots of creators in our community creating apps with property wrappers then writing about their experiences, and we’d like to share a few of our favorites with you here.
In her talk on property wrappers from dotSwift 2020, Erica Sadun teaches us why property wrappers help us specify behavior contracts at the point of declaration rather than the point of use. Erica has been one of the most active participants in the Swift Evolution process – we really appreciate her work! Another great talk comes from Stewart Lynch, who demonstrates how both wrapped values and projected values are useful when working with property wrappers, showing in detail how we could use them in both UIKit and SwiftUI – you can find it here.
We have lots of great articles on the topic too: Sarun Wongpatcharapakorn shows how to initialize property wrappers and how projected values work, you can read advice from Antoine van der Lee on how property wrappers remove boilerplate code by replacing repeated work with a custom property wrapper, and Rudrank Riyam walks us through creating a wrapper to track device orientation – you can really see how efficient property wrappers are at simplifying our code.
If you want to go further, you’ll like this article from Donny Wals, where he shares his knowledge on writing custom property wrappers for SwiftUI using the DynamicProperty
protocol. If you follow Donny’s guide, you’ll see how property wrappers let us get fantastically concise code like this:
struct ContentView: View {
@Setting(\.onboardingCompleted) var didOnboard
var body: some View {
Text("Onboarding completed: \(didOnboard ? "Yes" : "No")")
Button("Complete onboarding") {
didOnboard = true
}
}
}
There are also lots of packages available to support property wrappers in our projects, including ValidatedPropertyKit from Sven Tiigi, which checks that strings match a certain regular expressions, sequences have a certain number of elements, and numbers lie within a particular range; and Burritos from Guillermo Muntaner, which is a whole library of example property wrappers you can utilize in your projects, including @Clamping
, @Expirable
, @Trimmed
and many more.
What are your favorite uses of property wrappers? Send us a tweet @swiftlang and let us know!