Home > Mobile >  Correct way to initialize class property with method
Correct way to initialize class property with method

Time:11-24

I'm doing a small game in Swift and I got stuck on initializing property with a class method.

 class Game {
 var height: Int
 var width: Int
 var board: [[String]] = createBoard()


 init(height: Int, width: Int) {
    self.height = height
    self.width = width
 }

 func createBoard() -> [[String]]{
   var gameBoard: [[String]] = []
    //working with width and height props from above
    //filling the board and returning
   return gameBoard
  }
 }

how can I set board value as a result of function createBoard()? (inside create board I'm working with height and width)

CodePudding user response:

Create the property lazily.

The benefit is the closure is not executed until the property is read the first time

class Game {
    var height: Int
    var width: Int
    lazy var board: [[String]] = {
        var gameBoard: [[String]] = []
        //working with width and height props from above
        //filling the board and returning
        return gameBoard
    }()


    init(height: Int, width: Int) {
       self.height = height
       self.width = width
    }
 }

CodePudding user response:

As @vadian told lazy is a good way of doing it. But I want to add something.

I think you need to make your height and width private, to prevent changing them from outside, lazy block will be called once and if you will change for ex. height from 10 to 100 you board calculation will not be called. If you need to change your game settings after initializing it so I will suggest another option to do it.

    class Game {
        var height: Int {
            didSet {
                board = self.updateGameBoard(height: height,
                                             width: width)
            }
        }
        var width: Int {
            didSet {
                board = self.updateGameBoard(height: height,
                                             width: width)
            } 
        }
    
        lazy var board: [[String]] = {
            return updateGameBoard(height: height, width: width)
        }()
    
        init(height: Int, width: Int) {
           self.height = height
           self.width = width
        }

        private func updateGameBoard(height: Int, 
                                     width: Int) -> [[String]] {
            var gameBoard: [[String]] = []
            //working with width and height props from above
            //filling the board and returning
            return gameBoard
        }
   }

This will allow you to change update the board reactive from outside by changing height or width

  • Related