2

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?

TylerP
  • 9,600
  • 4
  • 39
  • 43
Richard Topchii
  • 7,075
  • 8
  • 48
  • 115

1 Answers1

3

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

Reza Khonsari
  • 479
  • 3
  • 13
  • @TylerP it can be easily fixed by adding didSet to wrappedValue like: var wrappedValue: T? { didSet { self.wrappedValue = wrappedValue?.nonEmptyValue } } – Reza Khonsari Feb 19 '22 at 06:33