2

When creating an instance using the convenience initialiser the playground keeps giving me this error "error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0x7ffee5ae9ff8)" however when using the designated initialiser it works fine.

I'm not entirely sure if i'm setting the convenience initialiser correctly so that only the arsenal parameter is required when creating a new instance.

class FootballTeams {

 var liverpool: String
 var chelsea: String
 var manchesterunited: String
 var arsenal: String = "fourth"

 init(arsenal:String, chelsea:String,     
      liverpool: String, manchesterunited:String ) { //designated initialiser
    self.arsenal = arsenal
    self.chelsea = chelsea
    self.liverpool = liverpool
    self.manchesterunited = manchesterunited
}

 convenience init(arsenal: String){
    self.init(arsenal: arsenal) //call to designated initialiser   above
    self.arsenal = arsenal
}
}

let properInstance = FootballTeams(arsenal: "Overides stored  property value", chelsea: "a", liverpool: "b", manchesterunited: "b")
print(properInstance.arsenal)

let convenienceInstance = FootballTeams(arsenal: "This is an instance from the convenience init")
print(convenienceInstance.arsenal)

1 Answers1

4

You are running into an infinite loop, didn't you see the warning

All paths through this function will call itself

That means init(arsenal calls init(arsenal which calls init(arsenal which calls init(arsenal which calls init(arsenal which ...

To call the convenience initializer you have to call the designated initializer and provide default values

convenience init(arsenal: String) {
    self.init(arsenal: arsenal, chelsea:"sixth", liverpool: "first", manchesterunited: "fifth") //call to designated initialiser   above
}

The extra line self.arsenal = arsenal is redundant.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thanks for the explanation! I'm still new to Swift this really helps, is there a way in a convenience init can use the designated initialisers default values? Rather than providing default ones as you described above – anonymousSwift Mar 29 '19 at 12:08
  • Except `arsenal` there are no default values. A default value must be assigned in the declaration line. – vadian Mar 29 '19 at 12:12
  • ‍♂️ Thanks again! I understand where I was going wrong – anonymousSwift Mar 29 '19 at 12:14
  • 1
    And please conform to the naming convention that struct and class names start with a capital letter. – vadian Mar 29 '19 at 12:15