My favourite UserDefaults1 use-case is preserving User Interface states, one of the essential items on the list of every good Mac and iOS application.

UserDefaults is one of the most powerful examples of why I love writing programs for Apple hardware. It is easy to get started, performant, and got even simpler2 over time. Just two three lines of code and you wrote something to permanent storage. Which you can read at any time, so efficient, adding your caching code would even hurt performance3.

David Smith wrote an excellent guide to UserDefaults for DS Coder. I have learned something new from the article:

Having an alternate code path for “no value set” is also generally unnecessary, as you can provide a default value instead.

Thank you, David, for this excellent guide.

  1. Omitting NS prefix, it doesn’t exist in Swift. 

  2. There’s no need to call synchronize() method anymore. 

  3. UserDefaults optimised for reading.Â