gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:49:11 26 4
gpt4 key购买 nike

您好,我正在尝试制作一个国际象棋游戏,目前我正在尝试构建一个函数,给定两个国际象棋方 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com