Task

Validate the check digit of an ISBN-13 code:

   Multiply every other digit by  3.
   Add these numbers and the other digits.
   Take the remainder of this number after division by  10.
   If it is  0,   the ISBN-13 check digit is correct.


Use the following codes for testing:

   978-1734314502       (good)
   978-1734314509         (bad)
   978-1788399081       (good)
   978-1788399083         (bad)


Show output here, on this page



See also

   for details:   13-digit ISBN method of validation.       (installs cookies.)


func checkISBN(isbn: String) -> Bool {
  guard !isbn.isEmpty else {
    return false
  }
 
  let sum = isbn
    .compactMap({ $0.wholeNumberValue })
    .enumerated()
    .map({ $0.offset & 1 == 1 ? 3 * $0.element : $0.element })
    .reduce(0, +)
 
  return sum % 10 == 0
}
 
let cases = [
  "978-1734314502",
  "978-1734314509",
  "978-1788399081",
  "978-1788399083"
]
 
for isbn in cases {
  print("\(isbn) => \(checkISBN(isbn: isbn) ? "good" : "bad")")
}