Save UIColor With UserDefaults in Swift 5

Hassan El Desouky
Jul 22, 2019 · 2 min read

I wanted to save UIColor into 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 UIColor with UserDefaults so we will have to manipulate the type a bit.

We are going to convert UIColor to Data and save it as any?. To convert the type of UIColor, we will need to use a special method called NSKeyedArchiver.

"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 NSKeyedUnarchiver decodes 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 UserDefaults.

We’ve converted UIColor to Data and then saved it as Any?. Then, we used the unarchiver to unarchive data and return the UIColor.

Also, If you aren’t a designer you can also buy some great iOS App Templates and if you are more interested in React Native App Templates you can buy them from here they have a really great collection.

Better Programming

Advice for programmers.

Hassan El Desouky

Written by

CS Student 👨🏻‍💻 Developer  Optimist 🚀 “What you do at 8pm will determine your future.”

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade