Reputation: 997
I keep coming across this same problem. In the below code I would get an error because I'm running makePlayersFrom before I have initialised all the properties of the class.
I can put players as an optional variable but it shouldn't be and I think that would be bad design. I could also put the makePlayers functionality in the init class but I feel like that is also bad design (I'm no the best person to know however). Would anyone be able to show me how to do this keeping in the best design principals?
class Game {
let host:User
var players:[Player]
init(host:User, extraPlayers:Int) {
self.host = host
self.players = makePlayersFrom(host:host, extraPlayers:extraPlayers)
}
private func makePlayersFrom(host:User, extraPlayers:Int) -> [Player] {
// do stuff to get players
return players
}
}
Upvotes: 1
Views: 134
Reputation: 450
According to Apple documentation you are violating Two-Phase Initialization number 4:
Safety check 4 - An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete.
For this case I would suggest converting makePlayersFrom
into class method:
private class func makePlayersFrom(...)
And call it from the initializer as self. players = Game.makePlayersFrom(...)
As long as makePlayersFrom
is not accessing instance variables it should work just fine.
Upvotes: 2