Skip to main content

Understanding property wrappers in Swift and SwiftUI

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

Understanding property wrappers in Swift and SwiftUI 관련

SwiftUI by Example

Back to Home

Understanding property wrappers in Swift and SwiftUI | SwiftUI by Example

Understanding property wrappers in Swift and SwiftUI

Updated for Xcode 15

SwiftUI relies heavily on property wrappers to make our code easier to read, write, and maintain, but if you’ve never used them before you might wonder where all the @ and $ signs have come from – they can seem quite alien at first.

Although property wrappers are a general Swift feature since they were introduced in Swift 5.1, they are particularly common in SwiftUI – you’ll see @Published, @ObservedObject, @EnvironmentObject and many more, all with the purpose of helping reduce the amount of boilerplate in our code.

We’ll be going into detail on each one of SwiftUI’s property wrappers in the next few chapters, but just briefly it’s worth summarizing the basics:

  • Some property wrappers allow us to achieve effects that would otherwise not be possible, such as the way @State lets us modify properties inside a struct.
  • Some property wrappers specifically require you to have done extra work elsewhere, and may crash your app if that work isn’t done. For example, @FetchRequest expects you to have placed a Core Data managed object context into the environment ahead of time.
  • You may apply only one property wrapper at a time, which means @ObservedObject @Binding var value = SomeClass() is not allowed.
  • Even though some property wrappers look similar (looking at you, @Environment and @EnvironmentObject!) they are all different and it’s important you use them appropriately.
  • You can create your own property wrappers if you want, but this isn’t required to use SwiftUI.

That covers the basics, but to really understand how these property wrappers work it’s worth investigating them individually.

Similar solutions…
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to use Instruments to profile your SwiftUI code and identify slow layouts | SwiftUI by Example

How to use Instruments to profile your SwiftUI code and identify slow layouts
Building a menu using List | SwiftUI by Example

Building a menu using List
Answering the big question: should you learn SwiftUI, UIKit, or both? | SwiftUI by Example

Answering the big question: should you learn SwiftUI, UIKit, or both?

이찬희 (MarkiiimarK)
Never Stop Learning.