Hello everyone, I completed the challenge, but it seems to me that my code looks bad.
What I don't like:
-
I check if the user clicked on the cell before by comparing the name with the standard "Unknown", I think this is bad. If the default name is changed in the code, then the application will not work as it should. Is there any other way to track if the user has previously changed the name in a different way?
-
I don't like that I have to write the same code several times, namely to create two UIAlertController and create and add UIAlertAction for each. I tried to write a showAlert function that I could call and change only the text, but I didn't succeed.
func showAlert(title: String, message: String, indexPath: IndexPath) {
let person = people[indexPath.item]
let ac = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: "Cancel", style: .default))
ac.addAction(UIAlertAction(title: "OK", style: .default) { [weak self, weak ac] _ in
guard let newName = ac?.textFields?[0].text else { return }
person.name = newName
self?.collectionView.reloadData()
})
present(ac, animated: true)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let person = people[indexPath.item]
if person.name == "Unknown" {
showAlert(title: "Add username",
message: "", indexPath: indexPath)
} else {
let questionController = UIAlertController(title: "Delete user?",
message: "",
preferredStyle: .alert)
questionController.addTextField()
questionController.addAction(UIAlertAction(title: "Rename",
style: .default) { [weak self, weak questionController] _ in
guard let newName = questionController?.textFields?[0].text else { return }
person.name = newName
self?.collectionView.reloadData()
} )
questionController.addAction(UIAlertAction(title: "Cancel",
style: .cancel))
questionController.addAction(UIAlertAction(title: "Delete",
style: .default) { _ in
self.collectionView.deleteItems(at: [indexPath])
self.people.remove(at: indexPath.item)
})
present(questionController, animated: true)
}
}
}