Swift. UserDefaults. Property wrapper

Ace Rodstin
2 min readJul 9, 2022

--

Xcode

It is not possible to imagine at least one application that does not require saving user settings. Obviously, there are many solutions for these purposes, and each of them solves one, specific problem. Today we will talk about the UserDefaults storage and its usage.

Implementation

After researching existing solutions on the Internet, the following materials were found:

  1. Property wrappers in Swift
  2. Create the Perfect UserDefaults Wrapper Using Property Wrapper
  3. A better approach to writing a UserDefaults Property Wrapper

However, they all have several disadvantages:

  1. The value cannot be optional, so a default value must be set.
  2. Value cannot be an enum or OptionSet.
  3. All of them allow you to store unsupported data types in storage, so application crashes as a result.

But if you turn to the original source and study Apple’s AppStorage, then the only drawback inherent in this solution is the minimum version of iOS 14, as well as the dependence on the SwiftUI framework.
The propertyWrapper UserDefault is proposed below, which is devoid of all the listed disadvantages, while solving the problem.

It is worth noting that the use of propertyWrapper is much more convenient, since the code becomes much compact, and therefore it is easier to read.

Conclusion

Recently, since the advent of SwiftUI, @propertyWrapper has become much more popular. However, the use of such objects imposes additional restrictions. For example, you need to raise the minimum version of iOS and introduce an additional dependency on the SwiftUI framework. But this does not mean at all that you need to use what is, and an example of this was described in this article.

  1. Original article
  2. UserDefaults
  3. AppStorage

--

--

Responses (1)