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.
Any suggestions?
Thanks in Advance.
edit/update: Xcode 7.2.1 • Swift 2.1.1
Extensions
//
I've just put together the following function in swiftstub.com and it seems to work as expected.
The function loops through each character in the string you pass into it, and uses the
find
function to check if the character (value) exists in the sequence (alphabetArray), and if it does it returns the index from the sequence. The index is then added to the count and when all characters have been checked the count is returned.Assign the letters by iterating over them and building a dictionary with letters corresponding to their respective values:
Use Swift's built-in Array
reduce
function to sum up the letters returned from yourUITextViewDelegate
:Maybe you are looking for something like this:
The sequence
text.lowercaseString.unicodeScalars
( lower case text as unicode scalar ) is filteredfilter
keeping only the scalars that pattern match~=
with thelowerCase
range.reduce
sums all the filtered scalar values shifted by -96 (such that 'a' gives 1 etc.).reduce
starts from an accumulator (acc
) value of0
. In this solution the pattern match operator will just check for the scalar value to be betweenlowerCase.start
(a) andlowerCase.end
(z), thus there is no lookup or looping into an array of characters.I'd create a function something like this...
Then you can iterate the word...