The stock intake screen reads thirteen digits from a scan, but the backend cannot find the product. After someone enters the code manually, its leading zero disappears. Problems like these often arise between scanner output and the business model. Extracting EAN-13 validation into a pure Swift function and running it as a pre-build check on a cloud Mac lets you reject malformed input before passing a validated string to the lookup API.
Define the contract
This article covers EAN-13 only: input must contain exactly thirteen ASCII digits. The first twelve digits enter the calculation; the final digit is the check digit. The validator does not trim spaces, convert full-width digits, or pad short input.
A barcode is an identifier, not a quantity. Model properties, API fields, and persistence columns should all preserve it as a string. Converting it to an integer and adding zeros back later cannot recover what the original input actually was.
A valid check digit establishes only internal consistency. It does not prove that a product exists, that its source is trustworthy, or that it may be accepted into inventory. Business catalog checks must run separately.
The scanner adapter should also carry the barcode symbology. Even if another symbology produces a similar sequence of digits, these rules cannot be applied directly. If conversion is necessary, define a separate conversion entry point and tests rather than making the validator guess.
Implement the validator
Number the first twelve positions from left to right, starting at one. Odd positions have a weight of one; even positions have a weight of three. Take the weighted sum modulo ten, subtract that remainder from ten, then take modulo ten again to obtain a check digit from zero to nine.
Create EAN13Check.swift with the following implementation. The function returns either the original, validated string or a specific error. It does not provide user-facing messages.
enum EAN13Error: Error, Equatable {
case length
case character
case checksum
}
func validateEAN13(_ raw: String) -> Result<String, EAN13Error> {
guard raw.utf8.count == 13 else {
return .failure(.length)
}
let bytes = Array(raw.utf8)
guard bytes.allSatisfy({ $0 >= 48 && $0 <= 57 }) else {
return .failure(.character)
}
let sum = bytes.prefix(12).enumerated().reduce(0) {
total, item in
total + Int(item.element - 48)
* (item.offset.isMultiple(of: 2) ? 1 : 3)
}
let expected = (10 - sum % 10) % 10
guard expected == Int(bytes[12] - 48) else {
return .failure(.checksum)
}
return .success(raw)
}
Checking length before allocating the byte array avoids copying oversized input into the calculation. The byte-range check deliberately avoids a broad “numeric character” test, which might accept digits from other writing systems.
Errors have a fixed precedence: length first, then characters, then the check digit. Full-width input may therefore produce a length error first; that is part of the contract. The UI can show a single invalid-format message without exposing the internal error categories.
Lock in the test fixtures
Append the following assertions to the same file. The three valid codes are algorithm test fixtures, not evidence of any product catalog records. One specifically covers a leading zero.
let validCodes = [
"4006381333931",
"5901234123457",
"0123456789012"
]
for code in validCodes {
precondition(validateEAN13(code) == .success(code))
}
precondition(validateEAN13("") == .failure(.length))
precondition(validateEAN13("400638133393") == .failure(.length))
precondition(validateEAN13("40063813339310") == .failure(.length))
precondition(validateEAN13("4006381333932") == .failure(.checksum))
precondition(validateEAN13("400638133393A") == .failure(.character))
precondition(validateEAN13(" 006381333931") == .failure(.character))
precondition(validateEAN13("400638133393\n") == .failure(.character))
precondition(validateEAN13("4006381333931") !=
.success("4006381333931"))
Run this on a node with the Swift toolchain already installed and configured:
xcrun swift EAN13Check.swift
A successful run produces no output. If an assertion fails, the process exits with a nonzero status. Run this command as a separate pipeline step and preserve its exit status. Do not use compiler options that disable assertions.
The expected values for these fixed fixtures must be checked manually. Do not generate check digits with the function under test and use those results as the sole reference: the same weighting error could contaminate both the inputs and the assertions.
Expand coverage
Testing just one incorrect final digit can miss reversed weights. For each valid code, replace each digit in turn with each of the other nine digits. Every substitution at all thirteen positions must be rejected.
for code in validCodes {
let original = Array(code.utf8)
for position in original.indices {
for replacement in UInt8(48)...UInt8(57) {
guard replacement != original[position] else {
continue
}
var changed = original
changed[position] = replacement
let input = String(decoding: changed, as: UTF8.self)
precondition(validateEAN13(input) == .failure(.checksum))
}
}
}
Together, the three fixtures cover three hundred and fifty-one single-digit substitutions. This result applies only to single-digit errors; it must not be generalized into a claim that every possible modification is detectable.
In particular, do not assert that swapping any two adjacent digits must fail. If digits in positions with different weights differ by five, swapping them can leave the check digit valid. A checksum algorithm is not a tamper-protection mechanism.
Add cases for an oversized string, an embedded null byte, and a trailing tab, and confirm that they are rejected. If upstream input allows users to paste codes containing spaces, handle that in a separate normalization function and retain both the raw and normalized values. Do not silently change the behavior of the strict entry point.
Integrate with the pipeline
In a production project, move the function into the business module and the assertions into a unit test target. The command-line file is suitable only as a minimal reproduction. Have manual entry in the UI, scan callbacks, and bulk imports all call the same entry point so that three sets of rules do not gradually diverge.
Split acceptance testing into three layers: algorithm tests verify the weights and check digit; adapter tests verify that the symbology and raw string are preserved; persistence round-trip tests verify that leading zeros survive saving, reading, and API encoding.
Logging the failure reason and sample ID is enough; there is no need to write complete, real-world business barcodes to public logs. When a bulk import encounters an error, return the specific row number and reject that row. Do not “repair” it into a different valid code by deleting characters, adding zeros, or recalculating the check digit.
Finally, perform a negative acceptance test: temporarily reverse the odd- and even-position weights, confirm that the fixed fixtures cause the job to fail, then restore the implementation. The integration is complete only when the gate catches an incorrect implementation. A single green build is not enough to prove that the coverage is effective.
Frequently asked questions
Does a valid EAN-13 prove that a product exists?
No. It only confirms thirteen ASCII digits and a matching check digit. Verify product existence and ownership separately against a trusted business catalog.
Should I convert a barcode to an integer before validation?
No. Integer conversion loses leading zeros. Keep the original string, validate its UTF-8 bytes, and then calculate the check digit.
Add a dedicated Mac to your build queue
An entire physical Mac dedicated to your tasks. Choose a model, billing period, and node to set up your team’s own macOS runner.
Rent now