我正在做一个应用程序,用户可以猜测图像中的名称并检查它,我能够看到将图像的名称放入数组中并能够看到它,但我需要将输入字符串与数组
我已经尝试使用 if(inputfield == images[i]){ 返回“正确”否则{ false 当我输入Apple时,答案给我错误
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"
}
}
}
当我输入是苹果时,我预计会“正确”,但当我按下检查按钮时,它显示错误
最佳答案
您可以比较
字符串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:if
表达式周围没有括号。
编辑:
保持索引相同
关于arrays - 将输入字段与数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56833217/