I have checked questions sharing the same topic but none address this weird behaviour I am experiencing:
Say I have a simple old school struct
:
struct Person {
var name: String
var age: Int
}
And I want to overload the init
in an extension
like this:
extension Person {
init(name: String) {
self.name = name
self.age = 26
}
}
As you expected, this code would run just fine.
However, If I move the Person struct
to a different module
(a.k.a different framework) and expose it to my module like this:
public struct Person {
public var name: String
public var age: Int
}
If I now overload the init
in an extension
locally in my module
the compiler produces the following errors:
'self' used before 'self.init' call or assignment to 'self'
'self.init' isn't called on all paths before returning from initializer
The only way I found to avoid this problem is calling the original init
inside the overloaded one like this:
extension Person {
init(name: String) {
self.init(name: name, age: 24)
}
}
I personally find this behaviour to be pretty strange.
Am I missing something?
Actually this example works for me with only a warning saying Initializer for struct 'Person' must use "self.init(...)" or "self = ..." because it is not in module
. As far as I know it was by design that struct initialisers were enforced to be defined within the scope of the struct definition module since Swift 4.2. Check the motivation section in 'https://github.com/apple/swift-evolution/blob/master/proposals/0189-restrict-cross-module-struct-initializers.md'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With