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

前端 未结 5 2145
臣服心动
臣服心动 2020-12-21 01:15

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 =

相关标签:
5条回答
  • 2020-12-21 01:31

    edit/update: 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
    
        }
    
    }
    

    Extensions

    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
    
    0 讨论(0)
  • 2020-12-21 01:33

    Maybe you are looking for something like this:

    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
    

    The sequence text.lowercaseString.unicodeScalars ( lower case text as unicode scalar ) is filtered filter keeping only the scalars that pattern match ~= with the lowerCase range. reduce sums all the filtered scalar values shifted by -96 (such that 'a' gives 1 etc.). reduce starts from an accumulator (acc) value of 0. In this solution the pattern match operator will just check for the scalar value to be between lowerCase.start (a) and lowerCase.end (z), thus there is no lookup or looping into an array of characters.

    0 讨论(0)
  • 2020-12-21 01:36

    I've just put together the following function in swiftstub.com and it seems to work as expected.

    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 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.

    0 讨论(0)
  • 2020-12-21 01:42

    Assign the letters by iterating over them and building a dictionary with letters corresponding to their respective values:

    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
    }
    

    Use Swift's built-in Array reduce function to sum up the letters returned from your 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 讨论(0)
  • 2020-12-21 01:49

    I'd create a function something like this...

    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
    }
    

    Then you can iterate the word...

    let word = "hello"
    var score = 0
    
    for character in word {
        score += valueOfLetter(character)
    }
    
    0 讨论(0)
提交回复
热议问题