swift - 我如何交换对象属性 Swift

标签 swift copy swap

您好,我正在尝试制作一个国际象棋游戏,目前我正在尝试构建一个函数,给定两个国际象棋方 block ,交换方 block 上的棋子。每个方 block 都是一个具有可选 ChessPiece 对象的类。我目前的问题是,当我将一个棋子移动到另一个方 block 棋子属性时,两个棋子最终都指向同一个对象,因为它们指的是同一个方 block 属性。

 private func swapSquares(square1: Square, square2: Square) {

    if square1.chessPiece == nil && square2.chessPiece == nil {
        return
    }

    var square1ChessPiece: ChessPiece?
    var square2ChessPiece: ChessPiece?

    if let square1piece = square1.chessPiece {
        square1ChessPiece = square1piece
    }

    if let square2piece = square2.chessPiece {
        square2ChessPiece = square2piece
    }

    if let square1piece = square1ChessPiece {
        square1piece.frame = square2.frame
        square1piece.square = square2
        square2.chessPiece = square1piece    // after this, square1ChessPiece and Square2Chess become the same
    }
    if let square2piece = square2ChessPiece {
        square2piece.frame = square1.frame
        square2piece.square = square1
        square1.chessPiece = square2piece
    }
}

我是否需要对两个棋子进行深度复制以便轻松交换位置?否则,注释行似乎只会让两个棋子对象指向内存中的同一位置。

最佳答案

您可以使用 swap 方法并声明您的两个方法参数,并向它们添加关键字 inout:

struct ChessPiece {
    let piece: String
}
struct Square {
    let row: Int
    let col: Int
    var chessPiece: ChessPiece?
}

private func swapSquaresPieces(square1: inout Square, square2: inout Square) {
    swap(&square1.chessPiece, &square2.chessPiece)
}

var square1 = Square(row: 1, col: 1, chessPiece: ChessPiece(piece: "queen"))
var square2 = Square(row: 2, col: 2, chessPiece: ChessPiece(piece: "king"))

swapSquaresPieces(square1: &square1, square2: &square2)

print(square1)
print(square2)

这将打印

Square(row: 1, col: 1, chessPiece: Optional(ChessPiece(piece: "king")))

Square(row: 2, col: 2, chessPiece: Optional(ChessPiece(piece: "queen")))

关于swift - 我如何交换对象属性 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46967144/

相关文章:

ios - Swift:在向 UIImageView 添加边框时获取小条

copy - 如何轻松地将非 mut &[u8] 复制到 &mut [u8]

linux - 使用通配符复制

android - 只是从 Android API 7 中的 textview 复制?

algorithm - 错误 : no matching function for call to 'swap'

ios - 将 navigationController 嵌入到 tabBarController 中后,tabBarItem 区域在界面生成器中消失

ios - 在 Swift 4 中根据 Table View 高度动态调整布局

swift - 如何在仍然接收点击事件的同时使 OS X 应用程序无法聚焦?

javascript - 用于根据用户输入/最大值交换变量的 JS 函数

c - 在 Windows 上获取 C 中的总交换大小?