Apply a number to each letter in text swift2

心已入冬 提交于 2019-12-19 12:47:19

问题


I want to compare two entries in a UITextField giving a number to each letter and then compare the results of the addition of the letters from both fields.

Example:

a=1 b=2 c=3 d=4 e=5 f=6

textfield1= cae
textfield2= fca

Result is:

textfield1=9 and
textfield2=10


回答1:


You could use the unicode scalar representation of each character (look up ASCII tables) and sum these shifted by -96 (such that a -> 1, b -> 2 and so on). In the following, upper case letters will generate the same number value as lower case ones.

let foo = "cae"

let pattern = UnicodeScalar("a")..."z"
let charsAsNumbers = foo.lowercaseString.unicodeScalars
    .filter { pattern ~= $0 }
let sumOfNumbers = charsAsNumbers
    .reduce(0) { $0 + $1.value - 96 }

print(sumOfNumbers) // 9

Or, to simplify usage, create a function or String extension

/* as a function */
func getNumberSum(foo: String) -> UInt32 {
    let pattern = UnicodeScalar("a")..."z"
    return foo.lowercaseString.unicodeScalars
        .filter { pattern ~= $0 }
        .reduce(0) { $0 + $1.value - 96 }
}

/* or an extension */
extension String {
    var numberSum: UInt32 {
        let pattern = UnicodeScalar("a")..."z"
        return self.lowercaseString.unicodeScalars
            .filter { pattern ~= $0 }
            .reduce(0) { $0 + $1.value - 96 }
    }
}

Example usage for your case:

/* example test case (using extension) */
let textField1 = UITextField()
let textField2 = UITextField()
textField1.text = "cAe"
textField2.text = "FCa"

/* example usage */
if let textFieldText1 = textField1.text,
    let textFieldText2 = textField2.text {

        print(textFieldText1.numberSum) // 9
        print(textFieldText2.numberSum) // 10

        print(textFieldText1.numberSum
            == textFieldText2.numberSum) // false
}


来源:https://stackoverflow.com/questions/35927148/apply-a-number-to-each-letter-in-text-swift2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!