Validate a Swift Sudoku solver on a cloud Mac
When you add a “Check puzzle” button to a puzzle app, filling the board is only part of the job. Duplicate digits must be reported as invalid input, valid but contradictory clues must produce “no solution,” and a puzzle with two answers must never be labeled “unique.” Putting this logic into a repeatable test suite on a cloud Mac lets you validate changes to pruning strategies without opening the interface remotely and entering digits by hand each time.
Define four outcomes, not a Boolean
This article covers only standard 9×9 Sudoku. The input is 81 integers in row-major order: zero represents an empty cell, and all other values must be between one and nine. Given digits must not repeat within any row, column, or box.
“Invalid” and “no solution” must remain distinct. The former violates the input constraints; the latter passes the basic checks but cannot be completed. A complete, valid board is itself one solution and must not return a count of zero just because it has no empty cells.
Finding one solution proves only that the puzzle is solvable. Establishing uniqueness requires further search; once a second solution is found, the search can stop without enumerating the remaining answers.
The original board must also remain unchanged after the call. A check operation must not silently fill in the user’s draft or leave behind digits from the last attempted solution.
Cap the solution count and pair every change with an undo
Create SudokuCheck.swift in your development directory on the cloud Mac and save the following code. It selects the empty cell with the fewest candidates first and backtracks immediately if a cell has no candidates. The priority here is correctness that is easy to audit, so the implementation uses neither bitwise operations nor shared caches.
enum Verdict: Equatable {
case invalid, none, unique, multiple
}
func classify(_ input: [Int]) -> Verdict {
guard input.count == 81,
input.allSatisfy({ (0...9).contains($0) })
else { return .invalid }
var board = input
func allowed(_ value: Int, at index: Int) -> Bool {
let row = index / 9
let col = index % 9
for k in 0..<9 {
if board[row * 9 + k] == value { return false }
if board[k * 9 + col] == value { return false }
}
let top = row / 3 * 3
let left = col / 3 * 3
for r in top..<(top + 3) {
for c in left..<(left + 3) {
if board[r * 9 + c] == value { return false }
}
}
return true
}
for i in board.indices where board[i] != 0 {
let value = board[i]
board[i] = 0
let valid = allowed(value, at: i)
board[i] = value
if !valid { return .invalid }
}
var solutions = 0
func search() {
if solutions >= 2 { return }
var chosen: Int?
var choices: [Int] = []
for i in board.indices where board[i] == 0 {
let candidates = (1...9).filter {
allowed($0, at: i)
}
if candidates.isEmpty { return }
if chosen == nil || candidates.count < choices.count {
chosen = i
choices = candidates
}
}
guard let index = chosen else {
solutions += 1
return
}
for value in choices {
board[index] = value
search()
board[index] = 0
if solutions >= 2 { break }
}
}
search()
precondition(board == input)
switch solutions {
case 0: return .none
case 1: return .unique
default: return .multiple
}
}
When validating a given digit, temporarily clear its cell; otherwise, it will conflict with itself. After every recursive call, reset the cell to zero before checking whether two solutions have been found. Reversing that order would let an early-exit path skip the undo step. The invariant check at the end is specifically there to catch this kind of implementation error.
The array is a local copy, so separate calls do not share search state. If you later introduce row and column candidate caches, their updates and rollbacks must follow the same backtracking path.
Cover all four outcomes with fixed boards
Append the following code to the same file. The fixture parser accepts only decimal digits: it does not strip whitespace or ignore unknown characters, which prevents test data from being silently corrected.
func digits(_ text: String) -> [Int] {
precondition(text.utf8.allSatisfy { (48...57).contains($0) })
return text.utf8.map { Int($0 - 48) }
}
let puzzle = digits(
"530070000600195000098000060800060003400803001" +
"700020006060000280000419005000080079"
)
let solved = digits(
"534678912672195348198342567859761423426853791" +
"713924856961537284287419635345286179"
)
var duplicate = puzzle
duplicate[2] = 5
var impossible = puzzle
impossible[2] = 1
precondition(classify(puzzle) == .unique)
precondition(classify(solved) == .unique)
precondition(classify(duplicate) == .invalid)
precondition(classify(impossible) == .none)
precondition(classify(Array(repeating: 0, count: 81)) == .multiple)
precondition(classify(Array(repeating: 0, count: 80)) == .invalid)
var outsideRange = puzzle
outsideRange[0] = 10
precondition(classify(outsideRange) == .invalid)
for _ in 0..<3 {
precondition(classify(puzzle) == .unique)
precondition(classify(impossible) == .none)
}
The unsolvable fixture is not made by arbitrarily removing a few digits. The original puzzle has exactly one solution, in which the third cell is four. Fixing that empty cell to one creates no immediate duplicate in its row, column, or box, but it rules out the original puzzle’s only solution. The result must therefore be “no solution.”
The empty board exercises the multiple-solutions result and early termination; it is not a performance benchmark for real puzzles. Repeatedly alternating between solvable and unsolvable fixtures can expose mistakes such as a global counter or state reused across calls.
Run remotely and preserve failure evidence
First confirm the active command-line toolchain, then compile and run:
set -eu
xcrun swift --version
mkdir -p .build
xcrun swiftc -Onone SudokuCheck.swift -o .build/sudoku-check
.build/sudoku-check
A successful run produces no text output and exits with code zero; a failed assertion makes the process exit with a nonzero code. Keep -Onone here rather than switching to -Ounchecked, which removes checks. Automated jobs must preserve the program’s exit code directly, not treat successful executable generation as proof that the tests passed.
Failure records should include at least the commit identifier, toolchain version, fixture name, and expected result. Obtain permission before logging boards submitted by users. Prefer the hand-crafted, fixed data in this article for the regression suite.
Separate correctness checks from performance budgets
Before committing, check each requirement: short inputs and out-of-range digits are rejected; a complete board counts as one solution; unsolvable input is not mislabeled as invalid; an empty board returns after the second solution is found; and every return path restores the working board.
Add digit-renaming tests as well: apply a one-to-one mapping to the digits one through nine while leaving zero unchanged. The original puzzle’s uniqueness classification must stay the same. Swapping two rows within the same band of boxes must not change the solution-count category either. These transformations complement fixed fixtures but do not replace tests with known answers.
For untrusted input, the search also needs a node budget or cancellation checks. Exhausting the budget must return a separate “incomplete” status, not masquerade as “no solution” or “unique.” This implementation does not include that production safeguard and should not process arbitrary puzzles directly on the UI’s main thread.
Finally, put the solver core in a separate test target, leaving the UI layer to verify input conversion and result presentation. The command-line checks on the cloud Mac then cover classification logic, while simulator tests cover user interactions, giving each kind of failure a clear place to investigate.
Frequently asked questions
Does finding the first solution prove that a Sudoku is unique?
No. Continue until a second solution is found or the search is exhausted. Exactly one solution after an exhaustive search establishes uniqueness.
Do these checks require an iOS simulator?
No. The solver uses only Swift arrays and integers, so the fixtures run from the command line. Test the mapping between UI input and solver results separately.
Cloud Mac rentals by project term
Get an entire physical Mac mini for your exclusive use—not a virtual machine. Choose daily, weekly, monthly, or quarterly billing. It shuts down at the end of your term, with no automatic renewal or charges.
Choose a configuration and rental term