Basically, a property wrapper is a common data structure that will help to read/write access to a property with adding some extra behavior.

Property wrapper is also known as Property delegates. It is available from Swift 5.1.

Let’s take a look in example which will help to use UserDefaults with ease.

@propertyWrapper
struct UserDefault<T> {
    let key: String
    let defaultValue: T

    init(_ key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}

In this code snippet don’t get confused with Foundation’s UserDefaults class. we created new structure without ‘s’ by applying @proopertyWrapper attribute.

We’ve taken two properties named ‘key’ and ‘defaultValue’ in them we’ll store UserDefaults’ key and it’s default value. Let’s go in deep.

struct MTUserDefaults {
    
    @UserDefault("isLoggedIn", defaultValue: false)
    static var isLoggedIn: Bool
    
    @UserDefault("launchCount", defaultValue: 0)
    static var launchCount: Int
    
    @UserDefault("username", defaultValue: nil)
    static var username: String?
    
}

In this new structure we’ve taken 3 properties ‘isLoggedIn’, ‘launchCount’ and ‘username’ by applying our proertyWrapper attribute. We’ve passed key and defaultValue to it.

Now let’s take a look how to use in actual code.

//To write
MTUserDefaults.isLoggedIn = true

//To read
print(MTUserDefaults.username ?? "No username found")

Leave a Reply

Your email address will not be published. Required fields are marked *