I am creating a chess application on swift. I'm trying to create a deep copy of my pieces so as to check if the new state would prevent an incoming check from the opposition. The deep copy would consist of the proposed move and it will utilize a function isKingUnderCheck()
to validate if the move helps avoid the check. So far I've looked through multiple websites and I've found many that talk about deep copying array, however, I'm still unsure about how to deep copy a Set of objects.
I've stored my pieces as a set let pieces: Set<ChessPiece>
.
I've set up NSCopying for my ChessPiece
class as shown below.
Lastly, I tried to create a function that takes in Set<ChessPiece>
to return a deep copy. However, I am unable to do so and it displays an error Cannot convert return expression of type '[Any]' to return type 'Set<ChessPiece>'
.
ChessPiece Class
class ChessPiece: NSObject, NSCopying {
func copy(with zone: NSZone? = nil) -> Any {
return type(of: self).init(self)
}
required init(_ piece: ChessPiece) {
col = piece.col
row = piece.row
isWhite = piece.isWhite
}
static func == (lhs: ChessPiece, rhs: ChessPiece) -> Bool {
lhs.col == rhs.col && lhs.row == rhs.row && lhs.isWhite == rhs.isWhite
}
var col: Int
var row: Int
let isWhite: Bool
init(col: Int, row: Int, isWhite: Bool) {
self.col = col
self.row = row
self.isWhite = isWhite
}
}
deepCopyPieces function
private func deepCopyPieces(pieces: Set<ChessPiece>) -> Set<ChessPiece> {
let tempPieces = pieces.map{$0.copy()}
return tempPieces
}
It is worth noting that Set<ChessPiece>
includes extensions of ChessPiece such as class KnightPiece: ChessPiece
.
I'm not so sure if I am doing this correctly as this is the first time I'm doing a project of this scale, thank you in advance for all your responses. Thank you for your time.