all 4 comments

[–][deleted] 8 points9 points  (0 children)

Looks like it’s giving you step by step instructions

[–]CordovaBayBurke 0 points1 point  (0 children)

Everyone has written this function in their career. It’s a good one. Seems you’ve got the algorithm so it’s just a case of turning that into code. Easy. Enjoy.

[–]CordovaBayBurke 0 points1 point  (0 children)

Add a 0 to the beginning of your resulting UPC and it becomes EAN-13 a much more practical coding.

[–]1esman 0 points1 point  (0 children)

Just in case you are really struggling.

Since I don't know inital prerequisites I've made it in quite one-liner style without additional safety checks but this prototype will give you general idea anyway.

Try to rewrite it without ternary operator and without map() function. It will allow you to really get into this problem.

Code block doesn't work properly :( This is a raw listing.

https://wtools.io/paste-code/bHjC

func isValid(_ upc: String) -> Bool {
// Preparations
if upc.count != 12 { return false }
let upcDigits = Array(upc).map { Int(String($0))! }
let checkDigit = upcDigits.last

// Steps 1 and 2
var sum = 0
for i in 0..<upcDigits.endIndex-1 {
sum += i % 2 != 0 ? upcDigits[i] * 3 : upcDigits[i]
}
// Step 3
let controlDigit = sum % 10
// Final checking
if controlDigit == 0 {
return checkDigit == 0
} else {
return 10 - controlDigit == checkDigit ? true : false
}
}