Questions about UserDefaults.standard property

Hey guys, I'm picking up Swift and making progress through Paul Hudson's Hacking with Swift course. I've have a questions regarding UserDefaults.standard. I notice that there are other classes that use a similar property called .standard and I was wondering what's going on here? Is this some sort of design pattern being implemented? Why am I using the .standard property to get an instance of the class instead of just initializing a new object of the class from these classes? Some guidance would be much appreciated. Thank you! Also if you have a link or resources that could explain it to me I'd love to bookmark it and reference it! Thanks again.

UserDefaults.standard is an example of the singleton pattern representing a UserDefaults instance of the standard environment. In general, a singleton is single instance of a value available globally, typically accessed through the type. E.g. UserDefaults.standard, FileManager.default, SomeType.shared. Now, these instances aren't technically singletons, as many of these types can be instantiated separately from their singleton instance, but Swift doesn't usually enforce that requirement, as the greater flexibility is useful for a variety of things.

Implementing your own singleton can be done by creating a static or class property on a type:

struct SomeType {
    static let shared = SomeType()
}
1 Like

Great thanks @Jon_Sheir! Also, since it's possible that we can instantiate separately from the singleton instance what would be the advantage in doing so rather than just using the singleton instance. Is just common practice to use the singleton instance unless there is some niche case not to?

There are a lot of opinions about proper singleton usage but simply put, being able to separately instantiate has a lot of advantages over enforced single instances. These include being able to customize your own instance, like you can for UserDefaults, or being able to create test instances while using the singleton normally.

2 Likes

since it's possible that we can instantiate separately from the
singleton instance what would be the advantage in doing so

Jon_Shier highlighted some good examples but I wanted to add another one that you might find interesting, specifically related to FileManager. This has a delegate property that you can populate to monitor the progress of long-running operations (think moves and copies). To use this effectively you have to create your own instance of FileManager.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

3 Likes

Thanks eskimo!