![]() Despite the fact that bool(forKey:) exists to solve this specific problem, I still see this happen in large codebases. Often, some manually written wrappers around UserDefaults will generically use object(forKey:) to get the value, which leaves you with a “truthy” result of either true, false, or nil. Usually this takes the form of an “isFirstAppLaunch” key with a Bool value. This means that in many cases we can be sure a value exists in UserDefaults.Ī common problem I see in codebases is a key-value pair for determining if the app is being launched for the first time by a user. If you provide a default value using register(defaults:), then retrieving it will always return something (i.e., a non-optional value). Most developers agree that we should try to eliminate optionals in Swift as much as possible. Related to the “default value problem” is the use of optionals. Also, it is only available in iOS 14 and above. If using this, you would need to manually call register(defaults:) with all of your key-value pairs somewhere during your app startup flow. Surprisingly, SwiftUI provides an property wrapper that also gets default values wrong. You can call -registerDefaults: as many times as you like, and it will combine the dictionaries that you pass it, which means you can keep registration of settings near the code that cares about them. It avoids doing disk writes during app launch, which slow things down and wears out disks.It’s automatically overridden by anything the user sets, so there’s no need to wrap it in an if statement to check if you should avoid doing it.It’s never stored to disk, so it’s impossible to confuse it with a value set by a user.The first way is to check for nil and return a default value if needed. The “default value problem” manifests in two ways. If you think you know everything there is to know about UserDefaults, wait until you read David Smith’s excellent (“unofficial”) documentation, NSUserDefaults in Practice. There is even a somewhat recent thread on the Swift forums about this exact issue. Unfortunately, most libraries and codebases implement default values incorrectly, which often also leads to a poor design regarding optional and non-optional values that are stored in UserDefaults. This is a convenient approach and removes common boilerplate for saving and retrieving values from UserDefaults. Since property wrappers were introduced in Swift, one of the most common (and best) use cases has been to implement a property wrapper where the underlying value is stored in UserDefaults. In fact, I have never worked on a single production codebase at a company where this was done accurately. Specifically, most developers do not handle default values correctly. UserDefaults is one of the most misused APIs on Apple platforms.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |