Swift. UserDefaults. Property wrapper
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.
After researching existing solutions on the Internet, the following materials were found:
- Property wrappers in Swift
- Create the Perfect UserDefaults Wrapper Using Property Wrapper
- A better approach to writing a UserDefaults Property Wrapper
However, they all have several disadvantages:
- The value cannot be optional, so a default value must be set.
- Value cannot be an enum or OptionSet.
- 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.
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.