How to create a Settings manager in Swift 5.1

Narlei Moreira
2 min readJun 4, 2019

Think that you need to work with UserDefaults (or Keychain…) to save if user is logged in, or if onboarding is already showed.

Your code looks like it:

My propose is replace for it:

Pros:

  • Pattern with property names;
  • If you need change UserDefaults to a Database (or something else) you will need change 2 lines;
  • It’s clear to Understand AppSettings — SOLID
  • Setting value it’s easy
  • Getting value it’s type safety

Cons:

  • Need Swift 5.1.

Let’s code:

Create a Playground:

Import Foundation:

import Foundation

Now we will create an Enum! Yes an Enum!

The next step is create a subscript method:

Running this code you can use:

Ok… but is not beautiful :( But wait!

Now we will create a New Enum inside AppSettings AND make some changes:

Running this code you can use:

Ok, more useful, with patterns but I still unwrap and verify the type. (as? Bool)

The solution… It’s here:

An extension that convert to types, like UserDefaults do.

Now our code looks like:

You can use and separate enum with key, to have a file with settings keys.

I hope I can turn your code better!

--

--