Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cycle through the entire alphabet with Swift while assigning values?

I am trying to cycle through the entire alphabet using Swift. The only problem is that I would like to assign values to each letter.

For Example: a = 1, b = 2, c = 3 and so on until I get to z which would = 26.

How do I go through each letter in the text field that the user typed while using the values previously assigned to the letters in the alphabet?

After this is done, how would I add up all the letters values to get a sum for the entire word. I am looking for the simplest possible way to accomplish this but works the way I would like it to.

like image 586
Bigfoot11 Avatar asked Mar 05 '15 22:03

Bigfoot11


1 Answers

edit/update: Xcode 12.5 • Swift 5.4


extension Character {
    static let alphabetValue = zip("abcdefghijklmnopqrstuvwxyz", 1...26).reduce(into: [:]) { $0[$1.0] = $1.1 }
    var lowercased: Character { .init(lowercased()) }
    var letterValue: Int? { Self.alphabetValue[lowercased] }
}

extension String {
    var wordValue: Int { compactMap(\.letterValue).reduce(0, +) }
}

Character("A").letterValue    // 1
Character("b").letterValue    // 2
Character("c").letterValue    // 3
Character("d").letterValue    // 4
Character("e").letterValue    // 5
Character("Z").letterValue    // 26
"Abcde".wordValue    // 15
like image 100
Leo Dabus Avatar answered Nov 15 '22 07:11

Leo Dabus