Mastering AppStorage in SwiftUI

fatbobman ( 东坡肘子)
7 min readApr 12, 2023

Preface

In Apple's ecosystem of applications, developers more or less use UserDefaults. Personally, I prefer to save user-customizable configuration information (precision, units, colors, etc.) in UserDefaults. As the configuration information increases, the use of @AppStorage in SwiftUI views becomes more and more common.

In [Health Notes 3], I plan to provide users with more custom options, and the simple calculation is that there will be 40-50 items. In the configuration view, all the UserDefaults content used will be injected into the code.

This article discusses how to use @AppStorage elegantly, efficiently, and safely in SwiftUI, without relying on third-party libraries, to solve the pain points in current @AppStorage usage:

  • Limited supported data types
  • Tedious declaration
  • Easy to have spelling mistakes in the declaration
  • A large number of @AppStorage cannot be uniformly injected

Stay ahead with the latest updates and deep insights on Swift, SwiftUI, Core Data, and SwiftData. Subscribe to Fatbobman’s Swift Weekly to get exclusive articles, tips, and curated resources delivered…

--

--