我正在做一个应用程序,用户可以在这个应用程序中猜出图像中的名称并检查它,我可以看到将图像的名称放在数组中,并且能够看到它,但我需要将输入字符串与数组进行比较。
我已经尝试使用if(inputfield == imagesi){ retun“更正”,否则,当我输入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"
}
}}
当我输入的是苹果时,我被期望退出“正确”,但是当我按下检查按钮时,它显示为假。
发布于 2019-07-01 09:53:06
您可以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:没有if表达式的括号。
编辑:
使索引保持不变
发布于 2019-07-01 09:35:56
比较文本的lowercased()版本,即
if(images[i] == tr.lowercased()){
checkLabel.text = "Correct"
}
else {
checkLabel.text = "false"
}你可以把它缩短到,
checkLabel.text = (images[i] == tr.lowercased()) ? "Correct" : "false"https://stackoverflow.com/questions/56833217
复制相似问题