The UserDefaults Wrapper

After understanding how property wrapper works, we are now ready to start implementing our UserDefaults wrapper. To recap, our property wrapper needs to keep track of the auto-login on/off status, as well as the user's username.

By using the concept we discussed above, you can easily convert the Printable property wrapper into a property wrapper that will write to or read from UserDefaults during a property read/write operation.

Here, we named our property wrapper Storage . It has two properties which are key and defaultValue .

key will be the key to use when reading and writing to UserDefaults , and defaultValue is the value to return when there is no value in UserDefaults .

With the Storage property wrapper ready, we can start implementing the UserDefaults wrapper. It is pretty straightforward, we just need to create a username variable that is wrapped by the Storage property wrapper.

Do note how you can initialize the Storage property wrapper with key and defaultValue .

With all that, the UserDefaults wrapper is finally ready to use. Let's see it in action:

At this point, let’s try to add the enableAutoLogin variable into our UserDefaults wrapper.

However, you will notice that the following two errors occurred:

Cannot convert value of type ‘Bool’ to expected argument type ‘String’ Property type ‘Bool’ does not match that of the ‘wrappedValue’ property of its wrapper type ‘Storage’