I wanted to save
UserDefaults so I googled it and couldn’t find any updated resource for Swift 5. Therefore, I came up with my own solution. Hopefully, it’s helpful.
There’s no straight way to save
UserDefaults so we will have to manipulate the type a bit.
We are going to convert
Data and save it as
any?. To convert the type of
UIColor, we will need to use a special method called
NSKeyedArchiver, a concrete subclass of
NSCoder, provides a way to encode objects (and scalar values) into an architecture-independent format that can be stored in a file. When you archive a set of objects, the class information and instance variables for each object are written to the archive. The companion class
NSKeyedUnarchiverdecodes the data in an archive and creates a set of objects equivalent to the original set.” — Apple
Therefore, let’s make an extension to the
Data and then saved it as
Any?. Then, we used the unarchiver to unarchive
data and return the