我试图使用
Swift在整个字母表中循环.唯一的问题是我想为每个字母赋值.
例如:a = 1,b = 2,c = 3,依此类推,直到我得到z = 26.
如何使用用户键入的文本字段中的每个字母,同时使用先前分配给字母表中字母的值?
完成此操作后,如何将所有字母值相加以获得整个单词的总和.我正在寻找最简单的方法来完成这个,但按照我希望的方式工作.
有什么建议么?
提前致谢.
编辑/更新:Xcode 7.2.1•Swift 2.1.1
原文链接:/swift/319534.htmlimport 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 } }
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