wrappedValue property should not be constant stored property!

As per the concepty of Propery Wrapper, When we create a wrapped Value , it can be constant stored property. So it is not usefull , if it supports creation of wrappedValue propery as constant stored property.
That is "public let wrappedValue: Int = 70" .

wrappedValue should be only computed property in my opinion. It must'nt support stored property behavior.

Because we can apply propery wrapper to only variables , not constant in first place.

I am sharing sample code, please look carefully, There is no advantage at all to create wrappedValue as stored constant property.

struct TwelveOrLess {
public let wrappedValue: Int = 70
private var number = 0

struct MyStruct {
@TwelveOrLess var val: Int

let a = MyStruct()

Because they require var in most contexts, it looks like that, but it's not a requirement.

For example, if you convert the code in this article to be

struct Clamped<T: Comparable> {
  var wrappedValue: T {
    min(max(_wrappedValue, range.lowerBound), range.upperBound)

  init(wrappedValue: T, range: ClosedRange<T>) {
    _wrappedValue = wrappedValue
    self.range = range

  private var _wrappedValue: T
  private var range: ClosedRange<T>

…you will get the error

❌ Cannot assign to value: 'x' is a get-only property

when attempting to mutate it:

@Clamped(range: 0...10) var x = 15
x = 5

But the exact code from the article will generate the same error, despite its wrappedValue being a constant, due to the auto-generated wrapping code.

This conversion results in worse code. When possible, a constant is a better YAGNI-style choice than a computed property for property wrappers or otherwise. Swift simplifies the model used by other languages whose best practices dictate always abstracting "fields" behind accessors.

1 Like