简体   繁体   中英

How to check if input from UITextField matches Core Data attribute in array?

I have a Core Data object that has two attributes, question and answer. I also have a view that has a label, a UITextField and a button. I want to show the question attribute in the label and then in the UITextField type in the answer attribute for that question to check if it is correct.

So, in viewDidLoad, I ran a fetch on my Card object and put the results into an array. I followed this Stack Overflow post in order to figure out how to iterate through the array to show each question attribute in the label, but now I am unsure how exactly to check the answer attribute for that question. Below is my source code:

var cardFetch = [Card]()
var count = 0
@IBOutlet weak var displayLabel: UILabel!
@IBOutlet weak var inputText: UITextField!

@IBAction func nextButton(sender: AnyObject) {
    displayLabel.text = cardFetch[count%cardFetch.count].question
    count++
}

Try something like:

@IBAction func nextButton(sender: AnyObject) {
   if let questionString = cardFetch[count%cardFetch.count].question as? String {
       displayLabel.text = questionString
       count++
   }   
}

@IBAction func checkAnswer(sender: AnyObject) {
    if let answerString = cardFetch[count%cardFetch.count].answer as? String {
        if let unwrappedTextfieldString = inputText.text as? String {  
            if answerString == unwrappedTextfieldString {
               // Do whatever you want here
            }
        }
    }   
}

Note the unwraps that make optional unwrapping crash safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM