Проверка турецкого идентификационного номера в Swift - PullRequest
0 голосов
/ 30 ноября 2018

Как я могу убедиться, что данный текст является турецким идентификационным номером?Я видел js версию здесь и версию phthon здесь

Turkish Identity Verification не проверяет, только если она числовая, она также имеет некоторые другие функции.Позвольте мне быть более ясным, он числовой и имеет 11 цифр.Например Предположим, что первые 9 цифр представлены d, а последние представлены c:

Identity Number = d1 d2 d3 d4 d5 d6 d7 d8 d9 c1 c2

10-ая цифра должна быть,

c1 = ( (d1 + d3 + d5 + d7 + d9) * 7 - (d2 + d4 + d6 + d8) ) mod10

11-ая цифра должна быть,

c2 = ( d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8 + d9 + c1 ) mod10

и никогда не начинается с "0". Например, "87836910956" - это турецкий идентификационный номер.

Ответы [ 3 ]

0 голосов
/ 30 ноября 2018

Просто простая реализация:

func verifyNumber(_ number: String) -> Bool {
    let pattern = "^[1-9][0-9]{10}$"

    // test that the length is correct and it's composed from digits
    guard number.range(of: pattern, options: .regularExpression) != nil else {
        return false
    }

    // convert characters to numbers
    let digits: [Int] = number.compactMap { Int(String($0)) }
    // split digits and check digits
    let d = Array(digits.prefix(9))
    let c = Array(digits.suffix(2))

    // calculate check digits
    let c1 = ((d[0] + d[2] + d[4] + d[6] + d[8]) * 7 - (d[1] + d[3] + d[5] + d[7])) % 10
    let c2 = (d.reduce(0, +) + c1) % 10

    // validate check digits    
    return c[0] == c1 && c[1] == c2
}
0 голосов
/ 30 ноября 2018

https://gist.github.com/befy/91dbdb9239fbf726cc1eaeeb5d9d6151 вы можете проверить мою суть, она короче в соответствии с другими.

func validateID(_ id: String) -> Bool {
 let digits = id.map {Int(String($0))} as! [Int]
 guard digits.count == 11, digits[0] != 0, digits[9] != 0 else { return false }
 let firstValidation = (digits[0] + digits[2] + digits[4] + digits[6] + digits[8]) * 7
 let secondValidation = digits[1] + digits[3] + digits[5] + digits[7]

 let tenthDigit = (firstValidation - secondValidation) % 10
 let eleventhDigit = (digits.reduce(0, +) - digits[10]) % 10
 return (digits[9] == tenthDigit && digits[10] == eleventhDigit) ? true: false
}

//usage
validateID("49673861228") //returns true and generated from https://www.simlict.com/

https://medium.com/@ntanyeri/swift-ile-tc-numaras%C4%B1-do%C4%9Frulama-24c7a9827ed Этот пост может помочь вам.

public class func validateCitizenshipID(ID: Int) -> Bool {
let digits = ID.description.characters.map { Int(String($0)) ?? 0 }

if digits.count == 11
{
    if (digits.first != 0)
    {
        let first   = (digits[0] + digits[2] + digits[4] + digits[6] + digits[8]) * 7
        let second  = (digits[1] + digits[3] + digits[5] + digits[7])

        let digit10 = (first - second) % 10
        let digit11 = (digits[0] + digits[1] + digits[2] + digits[3] + digits[4] + digits[5] + digits[6] + digits[7] + digits[8] + digits[9]) % 10

        if (digits[10] == digit11) && (digits[9] == digit10)
        {
            return true
        }
    }
}
return false
}
0 голосов
/ 30 ноября 2018

Используя guard, вы можете избавиться от глубокого вложения всех этих if s:

func isValidIdentityNumber(_ value: String) -> Bool {
    guard
        value.count == 11,
        let digits = value.map({ Int(String($0)) }) as? [Int],
        digits[0] != 0
    else { return false }

    let check1 = (
        (digits[0] + digits[2] + digits[4] + digits[6] + digits[8]) * 7
        - (digits[1] + digits[3] + digits[5] + digits[7])
    ) % 10

    guard check1 == digits[9] else { return false }

    let check2 = (digits[0...8].reduce(0, +) + check1) % 10

    return check2 == digits[10]
}

Обратите внимание, что в строке 4 приведение не удастся, если какой-либо из символов в value не конвертируется в Int из-за результата map, содержащего nil.

...