andtie
1
I have a question regarding the new @Namespace property wrapper from SwiftUI. In the example code, it is shown without a type-annotation. E.g.:
@Namespace var namespace
How is this possible in Swift? How can this be used for your own types / property wrappers?
1 Like
cukr
2
there's only one possible type that wrappedValue can be, which is Namespace.ID so there's no ambiguity what type namespace is
@propertyWrapper struct Foo {
var wrappedValue: Int = 0
}
struct Bar {
@Foo var test1
@Foo var test2: Int
// @Foo var test3: String // error: Property type 'String' does not match that of the 'wrappedValue' property of its wrapper type 'Foo'
}
print(Bar().test1) // prints 0
5 Likes
andtie
3
Thank you. So this is simply an improvement in the type inference algorithm in Swift 5.3?
With Swift 5.2.4 (Xcode 11.5) I get the error-message Type annotation missing in pattern.
Val
(Valentin)
5
I believe this has been the case from the start (when property wrappers were first introduced).
hborla
(Holly Borla)
7
What you're seeing here is default initialization of a property wrapper, which allows the wrapped property type to be inferred when possible. The ability to drop the type annotation from a default-initialized property wrapper was introduced in 5.3 (https://github.com/apple/swift/pull/30663), but this was previously supported by adding empty parentheses after the property wrapper attribute (e.g. @Namespace() var namespace). You can support this in your own property wrappers by providing a default initializer.
4 Likes