Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error of 'self' used before 'self.init' call or assignment to 'self' on init in a different module

Tags:

ios

swift

swift5

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?

like image 785
Hudi Ilfeld Avatar asked Jun 02 '20 11:06

Hudi Ilfeld


1 Answers

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'.

like image 94
Ashraf Tawfeeq Avatar answered Sep 22 '22 07:09

Ashraf Tawfeeq