Swift: Reset an instance
I'm wondering what the best-practice way to reset the attributes of an object are in swift. In the example code below, I'm looking for a way to reset the attributes of an object without creating a new object.
I understand that it would be best to make a new object, since it has the same effect, but I'm wondering if there is a way to do this without creating a new object. Also, I know that I could reset each attribute one by one, but in a class with lots of attributes, this would be a cleaner way to do so.
Example code:
var pingPong: Game = Game()
class Game {
var player1Score: Int
var player2Score: Int
init() {
self.player1Score = 0
self.player1Score = 0
}
func newGame() {
init() //Code in question
}
}
I've tried calling the class init()
from the newGame()
method, which throws an error. I've also tried calling self.init()
, after which I get an error telling me to instead use type(of: self).init()
, which throws yet another error Constructing an object of class type 'pingPong' with a metatype value must use a 'required' initializer
.
How can I accomplish resetting the attributes of an object without creating a new object?
There isn't a magic function that just resets all of the properties.
The first option is to reset all of the properties by hand:
class Game {
var player1Score: Int = 0
var player2Score: Int = 0
init() {
}
func reset() {
player1Score = 0
player2Score = 0
}
func newGame() {
reset()
//continue other newGame functions
}
}
If you had a lot of properties, though, this could get tedious. Instead, you could encapsulate your state into a value type (struct
) and create a new instance when you're ready for a new game. That might look like this:
struct GameState {
var player1Score = 0
var player2Score = 0
}
class Game {
var gameState : GameState
init() {
self.gameState = GameState()
}
func newGame() {
self.gameState = GameState()
//continue other newGame functions
}
}
That way, your Game
instance stays the same, but the state that it owns is reset.