比较输入字段和数组

时间:2019-07-01 09:33:07

标签: arrays swift xcode

我正在做一个应用程序,用户可以在其中猜测图像名称并进行检查,我能够看到将图像名称放入数组中并能够看到它,但是我需要将输入字符串与数组

我已经尝试使用if(inputfield == images [i]){ 重新调整“正确”,否则{否 当我输入苹果时,答案给我错误

let images: [String] =["apple","ball","cat","dog","elephant","frog","house","igloo","jar","kite","leaf","monkey","nose","orange","plane","queen","rope","sun","tub","goat"]
var i : Int = 1
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    guessInput.delegate = self
    imageView.image = UIImage(named: images[0])
}

@IBAction func nextButton(_ sender: UIButton) {// Able to show images
   if(i+1 > images.count){
       i = 0
    }
    imageView.image = UIImage(named: images[i])
    i += 1
    checkLabel.text = ""
    guessInput.text = ""
}
@IBAction func checkButton(_ sender: UIButton) {// Compare input with Array
    let tr = String(guessInput.text!)
    if(images[i] ==  tr){
        checkLabel.text = "Correct"
    }
    else{
        checkLabel.text = "false"
    }
}

}

当我输入的是苹果时,我应该会“正确”,但是当我按下检查按钮时,它会显示错误

2 个答案:

答案 0 :(得分:0)

比较文本的lowercased()版本,即

if(images[i] == tr.lowercased()){
    checkLabel.text = "Correct"
}
else {
    checkLabel.text = "false"
}

您可以将其缩短为

checkLabel.text = (images[i] == tr.lowercased()) ? "Correct" : "false"

答案 1 :(得分:0)

您可以return字符串compare,然后从字符串(caseInsensitive创建字符串是多余的。

String(guessInput.text!)

通过这种方式,编译器将抱怨表达式@IBAction func checkButton(_ sender: UIButton) {// Compare input with Array if images[i].compare(guessInput.text!, options: .caseInsensitive) == .orderedSame { checkLabel.text = "Correct" } else { checkLabel.text = "False" } } 中缺少空格,并且不注释编译器可以推断的类型。

=["apple"

您可以替换

let images = ["apple",...
var i = 0 // array indices start with 0

if(i+1 > images.count){
   i = 0
}
imageView.image = UIImage(named: images[i])
i += 1

i = (i + 1) % images.count imageView.image = UIImage(named: images[i]) 运算符使索引弯曲


最后,这是Swift:%表达式不带括号。

编辑:

要保持索引不变