我在执行代码的键盘上返回键时出现问题。我在过去尝试过,以下代码完美无缺:
func textFieldShouldReturn(textField: UITextField) -> Bool{
textField.resignFirstResponder()
valueOfLetter()
return true;
}
但是,由于某些原因,行valueOfLetter
上存在错误。
如果有必要,这是整个文件:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBOutlet weak var strWordValue: UILabel!
@IBOutlet weak var strInputField: UITextField!
func textFieldShouldReturn(textField: UITextField) -> Bool{
textField.resignFirstResponder()
valueOfLetter()
return true;
}
var TextField: UITextField!
func valueOfLetter(inputLetter: String) -> Int {
let alphabet = ["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"]
for (index, letter) in alphabet {
if letter = inputLetter.lowercaseString {
return index + 1
for character in word {
score += valueOfLetter(character)
}
}
}
return 0
}
}
错误是:“在调用中参数#1中缺少参数
行for (index, letter) in alphabet
上的另一个错误是:'String'不能转换为'([String,String])'
我不确定这些错误的含义或解决方法。
非常感谢任何意见或建议。
提前致谢。
答案 0 :(得分:8)
您的方法valueOfLetter
需要一个参数,您需要使用参数调用它,否则它将无效。例如:
valueOfLetter("x")
您的第二个错误正在发生,因为您正在使用用于迭代带有数组的字典的语法结构。使用内置的enumerate
函数迭代具有索引值的数组:
for (index, letter) in enumerate(alphabet) {
if letter = inputLetter.lowercaseString {
return index + 1
for character in word {
score += valueOfLetter(character)
}
}
}
答案 1 :(得分:3)
错误消息是因为您的[String]
数组无法快速枚举为一对索引和值。为此,您需要使用上面提到的enumerate
函数。
我建议将alphabet
数组提升为全局变量或成员变量。您可以将其标记为私有,以便在源文件外部不可见。
// A through Z
private let alphabet = ["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"]
您可以使用两个函数来计算单词的分数。第一个函数将计算特定字母的点数。第二个函数将获取一个字符串并通过它进行枚举,总结每个字母的点值。
func valueOfLetter(letter: Character) -> Int
{
let letterString = String(letter).uppercaseString
let index = find(alphabet, letterString)
return index != nil ? index! + 1 : 0
}
func scoreForWord(word: String) -> Int
{
let characters = Array(word)
return characters.reduce(0) { sum, letter in sum + valueOfLetter(letter) }
}
我知道这与您的初始设置有点不同。我只是想指出built-in Swift library functions are有多大用处。即filter
,map
和reduce
。
编辑:以下是通过UITextFieldDelegate
:
// This will be called every time the text changes in the UITextField
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
let currentWord = textField.text as NSString
let newWord = currentWord.stringByReplacingCharactersInRange(range, withString: string)
let score = scoreForWord(newWord)
// Do something with the score here
return true
}
// This will be called when the return key is pressed
func textFieldShouldReturn(textField: UITextField) -> Bool
{
let word = textField.text
let score = scoreForWord(word)
// Do something with the score here
return true
}