How do I iterate over the entire alphabet using Swift when assigning values?

I am trying to iterate over 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 will be = 26.

How can I go through each letter in the text box that the user entered when using the values ​​previously assigned to the letters in the alphabet?

After that, how would I collect all the meanings of the letters to get the sum for the whole word. I am looking for the simplest possible way to accomplish this, but it works the way I would like.

Any suggestions?

Thanks at Advance.

+4
source share
5

/: Xcode 7.2.1 β€’ Swift 2.1.1

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var strWordValue: UILabel!
    @IBOutlet weak var strInputField: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func sumLettersAction(sender: AnyObject) {
        strWordValue.text = strInputField.text?.wordValue.description

    }

}

extension String {
    var letterValue: Int {
        return Array("abcdefghijklmnopqrstuvwxyz".characters).indexOf(Character(lowercaseString))?.successor() ?? 0
    }
    var wordValue: Int {
        var result = 0
        characters.forEach { result += String($0).letterValue }
        return result
    }
}

enter image description here

func letterValue(letter: String) -> Int {
    return Array("abcdefghijklmnopqrstuvwxyz".characters).indexOf(Character(letter.lowercaseString))?.successor() ?? 0
}

func wordValue(word: String) -> Int {
    var result = 0
    word.characters.forEach { result += letterValue(String($0)) }
    return result
}


let aValue = letterValue("a")  // 1
let bValue = letterValue("b")  // 2
let cValue = letterValue("c")  // 3
let zValue = letterValue("Z")  // 26

let busterWordValue = wordValue("Buster") // 85
let busterWordValueString = wordValue("Buster").description // "85"

//

extension Character {
    var lowercase: Character { return Character(String(self).lowercaseString) }
    var value: Int { return Array("abcdefghijklmnopqrstuvwxyz".characters).indexOf(lowercase)?.successor() ?? 0 }
}
extension String {
    var wordValue: Int { return Array(characters).map{ $0.value }.reduce(0){ $0 + $1 } }
}

"Abcde".wordValue    // 15
+6

...

func valueOfLetter(inputLetter: String) -> Int {
    let alphabet = ["a", "b", "c", "d", ... , "y", "z"] // finish the array properly

    for (index, letter) in alphabet {
        if letter = inputLetter.lowercaseString {
            return index + 1
        }
    }

    return 0
}

...

let word = "hello"
var score = 0

for character in word {
    score += valueOfLetter(character)
}
0

, , :

let alphabet: [String] = [
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
]

var alphaDictionary = [String: Int]()
var i: Int = 0

for a in alphabet {
    alphaDictionary[a] = ++i
}

Swift reduce, , UITextViewDelegate:

func textViewDidEndEditing(textView: UITextView) {
    let sum = Array(textView.text.unicodeScalars).reduce(0) { a, b in
        var sum = a

        if let d = alphaDictionary[String(b).lowercaseString] {
            sum += d
        }

        return sum
    }
}
0

, - :

func alphabetSum(text: String) -> Int {
    let lowerCase = UnicodeScalar("a")..."z"
    return reduce(filter(text.lowercaseString.unicodeScalars, { lowerCase ~= $0}), 0) { acc, x in
        acc + Int((x.value - 96))
    }
}


alphabetSum("Az") // 27 case insensitive
alphabetSum("Hello World!") // 124 excludes non a...z characters

text.lowercaseString.unicodeScalars ( unicode) filter, , ~=, lowerCase. reduce , -96 (, 'a' 1 ..). reduce (acc) 0. , lowerCase.start (a) lowerCase.end (z), .

0

swiftstub.com , , .

func getCount(word: String) -> Int {
    let alphabetArray = Array(" abcdefghijklmnopqrstuvwxyz")
    var count = 0

    // enumerate through each character in the word (as lowercase)
    for (index, value) in enumerate(word.lowercaseString) {
        // get the index from the alphabetArray and add it to the count
        if let alphabetIndex = find(alphabetArray, value) {
            count += alphabetIndex
        }
    }

    return count
}

let word = "Hello World"
let expected = 8+5+12+12+15+23+15+18+12+4

println("'\(word)' should equal \(expected), it is \(getCount(word))")

// 'Hello World' should equal 124 :)

The function goes through each character in the string you pass into it and uses the function findto check if the character (value) exists in the sequence (alphabetArray), and if it does, it returns the index from the sequence. Then the index is added to the count, and when all the characters are marked, the counter is returned.

0
source

All Articles