【问题标题】:How to connect class properties with other class in Swift?如何在 Swift 中将类属性与其他类连接起来?
【发布时间】:2021-11-29 16:10:39
【问题描述】:

如何将我的班级游戏与班级董事会联系起来?我的意思是当我创建一个游戏时,棋盘将使用我为游戏设置的高度和宽度进行初始化。

PS 我不是经验丰富的程序员,刚开始学习课程

class Game {
    var height: Int
    var width: Int
    var player = Player()
    var board = [[String]]
    
    init(height: Int, width: Int) {
        self.height = height
        self.width = width
        self.board = Board().createEmptyBoard(height, width) //here's the error
    }
}

class Board {
    func createEmptyBoard(_ height: Int,_ width: Int) -> [[String]] {
        var gameBoard: [[String]] = []
        for i in 0...height - 1 {
            if i == 0 || i == height - 1 {
                gameBoard.append(Array(repeating: "????", count: width))
            } else {
                var basicLine = Array(repeating: "⬜", count: width)
                basicLine[0] = "????"
                basicLine[basicLine.count - 1] = "????"
                gameBoard.append(basicLine)
            }
        }
        return gameBoard
    }
}

class Player {
    var playerPosition = (vertical: 1, horizontal: 1)
    
    enum Move {
        case up
        case down
        case right
        case left
    }
    
    func moveAlien(direction: Move) {
        switch direction {
        case .up: playerPosition.vertical += 1
        case .down: playerPosition.vertical -= 1
        case .right: playerPosition.horizontal += 1
        case .left: playerPosition.horizontal -= 1
        }
    }
}

【问题讨论】:

  • 错误是什么?
  • 类 Board 应该包含 [[String]] 并且 Game 中的 board 属性应该是 Board 类型
  • 你能修正一下缩进吗?

标签: swift class oop


【解决方案1】:

您对Board 的声明不正确。

您需要将数组声明为let array: [String],而不是let array = [String]

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

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

我还建议在Board 上将createEmptyBoard 设为static 方法,因为如果Board 没有属性,则实例化它没有意义。

或者,Board 本身可以存储[[String]],而Game 可以将其board 存储为Board

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多