我想遍历枚举中的所有值,但考虑到某些条件,我想放弃并转到下一个值.任何在break
或continue
语句中的try ,如果编译器指出‘.allCases.forEach’不是‘func Test1’中的循环.
我想出的最好的解决办法是func test2
个,但它似乎"不快",我可以只有一堆嵌套的if
个块,看起来像是额外的.那么,如果不是循环,.allCases.forEach
又是什么呢?更重要的是,有没有一种不同/更好的方法来迭代enum
?
更新:添加了Func‘process FoolPower’,解决方案1作为目标的一个小示例.想想大棋盘吧.
enum directions: Int, CaseIterable {
case up = 0, upRight, right, downRight, down, downLeft, left, upLeft, invalid
}
func test1() {
print("forEach: ")
moveDirections.allCases.forEach {
if $0 == .up { () } // I want to { continue } here to next direction
if $0.rawValue == 4 { () } // or { continue } here to next direction
testPrint(test: $0)
}
}
func test2() {
print("for : ")
for direction in 0..<moveDirections.allCases.count {
if moveDirections(rawValue: direction) == .up { continue }
if direction == 4 { continue }
testPrint(test: moveDirections(rawValue: direction).self!)
}
}
func testPrint(test: moveDirections) {
print(test.self)
}
mutating func processFoolPower(foolPiece: gamePiece, owner: Bool) {
var testPiece: gamePiece = MockData.blankPiece
for direction in moveDirections.allCases {
let testSquare = foolPiece.location! + SquareShift(direction)
if testSquare < 0 || testSquare > 143 { continue } // test for off top/bottom of board
switch direction {
case .down, .up, .left, .right:
if isStraight(from: foolPiece.location!, to: testSquare) == .invalid { continue } // test for off sides of board
case .upLeft, .downLeft, .upRight, .downRight: ()
if isDiagonal(from: foolPiece.location!, to: testSquare) == .invalid { continue } // test for off sides of board
case .invalid: ()
}
testPiece = pieces.first(where: { $0.location == testSquare }) ?? MockData.blankPiece
if testPiece.status != .dead { executeKill(pieceId: testPiece.id, explanation: .blownUp) }
}
executeKill(pieceId: foolPiece.id, explanation: .exploded)
}