Ad

Property Wrapper: Change Empty To Optional

- 1 answer

I've created the following extension:

import Foundation

extension Collection {
    /// Returns `nil` if empty
    var nonEmptyValue: Self? {
        isEmpty ? nil : self
    }
}

Now I'd like to make it a property wrapper so I could use it like this:

final class MyClass {
    @NonEmpty
    var string: String? = "test"
}

The idea is that whenever an empty string is assigned to the property, it gets replaced with nil.

Is it even possible to create such a property wrapper (since String? and String are of different type) and how would I go about it?

Ad

Answer

I'm using your extension:

import Foundation

@propertyWrapper
struct NonEmpty<T: Collection> {
    
    var wrappedValue: T? {
        didSet {
            self.wrappedValue = wrappedValue?.nonEmptyValue
        }
    }
    
    init(wrappedValue: T?) {
        self.wrappedValue = wrappedValue?.nonEmptyValue
    }
}

extension Collection {
    /// Returns `nil` if empty
    var nonEmptyValue: Self? {
        isEmpty ? nil : self
    }
}

and the result is just like image below:

enter image description here

Ad
source: stackoverflow.com
Ad