Swift Property Wrappers

Property wrappers are a relatively new feature of Swift and can provide a lot of shortcuts. Say we want to store something in UserDefaults, or localize a string. We can use Property Wrappers to do this more easily. Here is an example of a wrapped localized value:

@propertyWrapper
struct LocalizedValue {
    private var key: String
    private let comment: String
    
    init(key: String, comment:String = "") {
        self.key = key
        self.comment = comment
    }
    
    var wrappedValue: String {
        get {
            return NSLocalizedString(key, comment: comment)
        }
        set {
            key = newValue
        }
    }
}

To use this we can just do the following:

@LocalizedValue(key: "test_value", comment: "a comment")
var theValue:String

This will store the key test_value in the variable and fetch it from your strings file by calling NSLocalizedString when you read it. You can also set the value of the variable which will set the key to a different value.