I think I found a bug in how Swift synthesizes memberwise initializers for structs.
Scenario A. Mixed non-optionals and optionals.
struct Foo {
var a: String
var b: Int?
}
Synthesizes:
Foo.init(a: String, b: Int?)
Scenario B. All optionals.
struct Foo {
var a: String?
var b: Int?
}
Synthesizes:
Foo.init(a: String?, b: Int?)
Foo.init() // why?
Scenario C. All optionals with explicit Optional
type.
struct Foo {
var a: Optional<String>
var b: Optional<Int>
}
Synthesizes:
Foo.init(a: Optional<String>, b: Optional<Int>)
I have a few questions:
Why would scenario B synthesize a parameterless init
, if I haven't explicitly defaulted every property to nil
?
And most importantly, why does this behavior only apply to properties declared with optional syntactic sugar ?
but not explicit Optional<T>
s?
I get the feeling this might be a compiler error.
Side note: how this affects property wrappers
This not only affects struct initializers, but also property wrapper initializers.
Scenario B applied to property wrappers.
@propertyWrapper
struct Bar {
var wrappedValue: String?
}
struct Foo {
@Bar
var a: String?
}
Synthesizes:
Foo.init(a: Bar)
Foo.init()
Foo.init() // repeated... why?
Scenario C half-applied to property wrappers.
@propertyWrapper
struct Bar {
var wrappedValue: Optional<String>
}
struct Foo {
@Bar
var a: String?
}
Synthesizes:
Foo.init(a: String?)
Foo.init()
Scenario C fully-applied to property wrappers.
@propertyWrapper
struct Bar {
var wrappedValue: Optional<String>
}
struct Foo {
@Bar
var a: Optional<String>
}
Synthesizes:
Foo.init(a: Optional<String>)
Conclusion
I expect ?
to produce the initializers that explicit Optional
s produce. However this is not happening at the moment. Am I correct in my expectation?