Last active
April 1, 2020 15:28
-
-
Save ghislainfrs/804c02197eebc18099dd334db9621717 to your computer and use it in GitHub Desktop.
Generate EAN13 check digit in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// EAN13CheckDigitHelper.swift | |
// | |
import Foundation | |
public struct EAN13CheckDigitHelper { | |
public enum EAN13Error: Error { | |
case mustOnlyContainDigits | |
case mustBe12DigitsLong | |
} | |
/// Generates a check digit from a partial EAN13. | |
/// | |
/// - Parameter barcode: a 12-digits EAN13 barcode without the check digit | |
/// - Returns: the check digit of the partial EAN13 barcode | |
public static func getCheckDigit(from barcode: String) throws -> Int { | |
guard CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: barcode)) else { | |
throw EAN13Error.mustOnlyContainDigits | |
} | |
guard barcode.count == 12 else { | |
throw EAN13Error.mustBe12DigitsLong | |
} | |
let sum = barcode | |
.compactMap({ Int(String($0)) }) | |
.enumerated() | |
.map({ (index, digit) in | |
digit * ((index % 2 == 0) ? 1 : 3) | |
}) | |
.reduce(0, +) | |
return (sum % 10 == 0) ? 0 : (10 - sum % 10) | |
} | |
/// Get the whole EAN13 barcode string from a partial EAN13. | |
/// | |
/// - Parameter barcode: a 12-digits EAN13 barcode without the check digit | |
/// - Returns: the barcode as a string with the check digit at its end | |
public static func getEAN13(from barcode: String) throws -> String { | |
barcode + String(try Self.getCheckDigit(from: barcode)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment