This IBAction brings up a UIAlertController with two text boxes. One box for name and one for age. I'm trying to make it so that the user does not have to enter their age if they don't want to. right now if they don't enter their age the app crashes right by the person.age = Int16(points!)!
line saying "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value". I am trying to use an if else statement stop this. What am I missing though?
@IBAction func addRowBtn(_ sender: Any) {
let alert = UIAlertController(title: "Add Person", message: nil, preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "Task"
}
alert.addTextField { (textField) in
textField.placeholder = "Points"
textField.keyboardType = .numberPad
}
let action = UIAlertAction(title: "post", style: .default) { (_) in
let name = alert.textFields?.first!.text!
let age = alert.textFields?.last!.text!
if name != nil && age != nil {
let person = Person(context: PersistenceServce.context)
person.name = name
person.age = Int16(age!)!
PersistenceServce.saveContext()
self.people.append(person)
self.table.reloadData()
}
if name != nil && age == nil {
let person = Person(context: PersistenceServce.context)
person.name = name
person.age = 0
PersistenceServce.saveContext()
self.people.append(person)
self.table.reloadData()
}
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
Aucun commentaire:
Enregistrer un commentaire