1

I coded a simple property wrapper in Swift and I tried to use Self and self to refer to the property wrapper struct/class Reference<T> in the projectedValue property:

@propertyWrapper
class Reference<T> {
    private var value: T
    
    init(wrappedValue: T) { value = wrappedValue }
    
    var wrappedValue: T {
        get { value }
        set { value = newValue }
    }
    
    var projectedValue: Self { self }
}

But it appears that Self is not referring to the type Reference<T>. For instance if I declare such property in a struct and then use the projectedValue:

struct Test {
    @Reference var value: Int = 1
}

let t = Test()
let ref = t.$value

The variable ref is of type Test instead of Reference<T>. This code does not compile and results in a segmentation fault but Xcode does not return any interactive error. To make the code work as expected I must declare it like this:

var projectedValue: Reference<T> { self }

This feels very weird, is it intended behavior or not? I checked Apple documentation but this behavior is not documented.

Louis Lac
  • 5,298
  • 1
  • 21
  • 36
  • I cannot reproduce this. I get a segfault, which is also weird... Why not do `var projectedValue: Reference { self }`? – Sweeper Jul 28 '20 at 09:52
  • Only reason is that `Self` is very convenient and I use this pattern everywhere in my code. – Louis Lac Jul 28 '20 at 09:54
  • 2
    This bug seems to have been reported multiple times: https://bugs.swift.org/browse/SR-12609 and https://bugs.swift.org/browse/SR-11152 for example. – Sweeper Jul 28 '20 at 09:57
  • Oh I was wrong the code does not compile either for me. However no interactive error are shown by Xcode and Xcode successfully infers the variable type. – Louis Lac Jul 28 '20 at 10:00

0 Answers0