0

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

zx485
  • 28,498
  • 28
  • 50
  • 59
  • 1
    Possible duplicate of [How do I cycle through the entire alphabet with Swift while assigning values?](http://stackoverflow.com/questions/28889172/how-do-i-cycle-through-the-entire-alphabet-with-swift-while-assigning-values) – Leo Dabus Mar 11 '16 at 01:55

1 Answers1

0

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
}
dfrib
  • 70,367
  • 12
  • 127
  • 192
  • Tks, that resolve my problem, but if i need upper case to? – Fabio Carlos Silva Mar 11 '16 at 11:39
  • @FabioCarlosSilva http://stackoverflow.com/questions/28889172/how-do-i-cycle-through-the-entire-alphabet-with-swift-while-assigning-values – Leo Dabus Mar 11 '16 at 14:09
  • @FabioCarlosSilva You can append the `.lowercaseString` property to the `String` representation of each character in `getNumberSum(...)` function above. I've now included this in my answer (`getNumberSum()` updated). For an alternative method using extensions, see the linked thread provided by Leo. – dfrib Mar 11 '16 at 14:38