Hello everyone! I just completed Project 8 challenge and I wanted to add something extra and experiment with closures again.
I noticed that the player has to manually clear the currentAnswer.text
after a simple "Wrong answer" UIAlertAction
is presented so I wanted to use its handler to do it automatically and save the user one step.
What I implemented worked but I'm still not sure if this is a strong reference cycle and if I should've used [weak self]
or [unowned self]
instead of _
. My guess is that it's NOT a strong reference cycle because the UIAlertController
doesn't hold a variable that changes other objects or methods in the view Controller (like the UITextField
and submit
method on Project 5 did) but it is only changing some attributes, am I on the right track?
Also, I wanted to call the clearTapped
method but since is expecting a UIButton
as sender
instead of a UIAlertAction
, I copied it. Is there any other way to perform this?
This is my code:
@objc func submitTapped(_ sender: UIButton) {
guard let answerText = currentAnswer.text else { return }
if let solutionPosition = solutions.firstIndex(of: answerText) {
activatedButtons.removeAll()
var splitAnswers = answersLabel.text?.components(separatedBy: "\n")
//debugPrint(splitAnswers ?? "splitAnswers is empty")
splitAnswers?[solutionPosition] = answerText
answersLabel.text = splitAnswers?.joined(separator: "\n")
//debugPrint(answersLabel.text ?? "answersLabel is empty")
//debugPrint("Solutions array joined = \(solutions.joined(separator: "\n"))")
currentAnswer.text = ""
score += 1
} else {
let ac = UIAlertController(title: "ERROR", message: "That's not the right answer", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Try again", style: .default)
{ _ in
self.currentAnswer.text = ""
for button in self.activatedButtons {
button.isHidden = false
}
self.activatedButtons.removeAll()
})
present(ac, animated: true)
score -= 1
}
if solutions.joined(separator: "\n") == answersLabel.text {
let ac = UIAlertController(title: "Well done!", message: "Are you ready for the next level?", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Let's go", style: .default, handler: levelUp))
present(ac, animated: true)
}
}
Thanks in advance for your insights, happy coding!
KB