swift - 如何使用 swift 检查文本字段的答案?
问题描述
我正在使用单个页面在 Xcode 中编写一个基本的测验应用程序,并且需要有关如何检查答案的帮助。我有一串匹配的问题和答案。当用户在文本字段中输入他的答案时,我如何检查它是否正确?
@IBOutlet var questionLabel:UILabel!
@IBOutlet var answerField:UITextField!
@IBOutlet var instructionsLabel:UILabel!
let questions:[String] = ["In what country is the Christ the Redeemer statue located in?", "In what country is Machu Picchu lacated in?", "In what country is the Taj Mahal located in?", "In what country is the Great Pyramids of Giza located in?","In what country is Petra located in?","In what country is the Great Wall located in?", "In what country is the ruins if Chichen Itza located in?"]
let answers:[String] = ["Brazil", "Peru", "India", "Egypt", "Jordan", "China", "Mexico"]
var currentQuestionIndex:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
currentQuestionIndex = questions.count - 1
}
@IBAction func showNextQuestion(sender:AnyObject){
if(currentQuestionIndex<questions.count-1) {
currentQuestionIndex = currentQuestionIndex + 1
} else {
currentQuestionIndex = 0
}
questionLabel.text = questions[currentQuestionIndex]
}
@IBAction func checkAnswer(){
}
}
解决方案
这是检查答案的一种方法
@IBAction func checkAnswer() {
guard let answer = answerField.text, !answer.isEmpty else {
//answer is empty
return
}
if answers[currentQuestionIndex].lowercased() == answer.lowercased() {
//correct answer found
} else {
//Incorrect answer
}
}
请注意,我没有编写任何代码来向用户显示结果,但是您可以有一个标签,您可以在其中写一条消息,而我刚刚写了一条评论。更高级的解决方案可能是将结果消息显示为警报或工作表。
推荐阅读
- laravel-livewire - 在编辑模式下打开页面时如何填充状态/区域/子区域选择?
- palantir-foundry - 如何在保留已删除行的同时合并增量数据集和快照数据集?
- concurrency - 在一个简单的并发程序中证明不变量(大学示例问题)
- docker - 在 Windows Server 2019 上使用 Balena-cli 部署时出现 Docker 错误“不是目录”
- javascript - 如何在 chrome ext 的弹出窗口中显示来自像素的调用?
- pandas - Pandas Dataframe 根据列值将值展平到单元格
- swift - Swift:数组已设置,但在访问时为空
- angular - Angular 语言服务悬停在 HTML 文件中的变量上,“$”不起作用
- c# - 根据请求 URL c# 模拟 HttpMessageHandler
- magento2 - 通过单个 API 调用自定义产品价格