So I've read the Wiki and related threads about optionals and force unwrapping, but I have the following problem. I'm doing the tutorial 'Start developing iOS' in which you build a small 'FoodTracker' app.
I've been getting the before mentioned error (Thread 1: Fatal Error: Unexpectedly found nil while unwrapping an Optional value). So I thought I would just make it a non-forced execution, but when I do this the cells (an image, a title and a star rating) come back empty. So the app will build and run, but the three examples aren't displayed.
When I make the cell.nameLabel.text = meal.name a comment, the error shifts to the next string (about the image).
It feels a bit like the app can't find the examples the tutorial lets you implement, 'sees nil' and returns an error..
Thanks you!
import UIKit
class MealTableViewController: UITableViewController {
//MARK: Properties
var meals = [Meal]()
override func viewDidLoad() {
super.viewDidLoad()
// Load the sample data.
loadSampleMeals()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return meals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "MealTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MealTableViewCell else {
fatalError("The dequeued cell is not an instance of MealTableViewCell.")
}
// Fetches the appropriate meal for the data source layout.
let meal = meals[indexPath.row]
**cell.nameLabel.text = meal.name (ERROR is here)
cell.photoImageView.image = meal.photo
cell.ratingControl.rating = meal.rating**
return cell
}
//MARK: Private Methods
private func loadSampleMeals() {
let photo1 = UIImage(named: "meal1")
let photo2 = UIImage(named: "meal2")
let photo3 = UIImage(named: "meal3")
guard let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4) else {
fatalError("Unable to instantiate meal1")
}
guard let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5) else {
fatalError("Unable to instantiate meal2")
}
guard let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3) else {
fatalError("Unable to instantiate meal3")
}
meals += [meal1, meal2, meal3]
}
}