The name UserDefaults
rather undersells the wide range of uses for which this feature of the Foundation framework is suitable. Any data that is reasonably simply structured can be stored with very little code in UserDefaults
, and there is no limit to the amount of data that can be stored (apart from the obvious limit to the device's storage).
However, if you're storing large amounts of data, we'll be looking at more suitable alternatives later in this chapter, and in the next.
UserDefaults
can save the following data types:
Bool
Number types
Array
Dictionary
Other types can be stored if they can be coded into Data
type objects:
Data
Foundation also provides convenience methods for the following commonly stored types that need serializing first:
Date
String
URL
For the UserDefaults
, we will create an extension.
Add an extension code to the CustomFileManager
class:
extension CustomFileManager { }