##概要
iOS開発の勉強を行うため、Start Developing iOS Apps (Swift)をやっているのですが、
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
が発生します。
swift
1import UIKit 2 3class MealTableViewController: UITableViewController { 4 5 //MARK: Properties 6 7 var meals = [Meal]() 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 12 //Load the sample data. 13 loadSampleMeals() 14 } 15 16 // MARK: - Table view data source 17 18 override func numberOfSections(in tableView: UITableView) -> Int { 19 20 return 1 21 } 22 23 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 24 25 return meals.count 26 } 27 28 29 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 30 31 //Table View cells are reused and should be dequeued using a cell identifier. 32 let cellIdentifier = "MealTableViewCell" 33 34 tableView.register(MealTableViewCell.self, forCellReuseIdentifier: cellIdentifier) 35 36 guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MealTableViewCell else { 37 fatalError("The dequeued cell is not an instance of MealTableViewCell") 38 } 39 40 //Fetches the appropriate meal for the data source layout. 41 let meal = meals[indexPath.row] 42 43 cell.nameLabel.text = meal.name 44 cell.photoImageView.image = meal.photo 45 cell.ratingControl.rating = meal.rating 46 47 return cell 48 } 49 50 //MARK: Private Methods 51 52 private func loadSampleMeals() { 53 54 let photo1 = UIImage(named: "Meal1") 55 let photo2 = UIImage(named: "Meal2") 56 let photo3 = UIImage(named: "Meal3") 57 58 guard let meal1 = Meal(name: "mesi1", photo: photo1, rating: 4) else { 59 fatalError("Unable to instantiate meal1") 60 } 61 62 guard let meal2 = Meal(name: "mesi2", photo: photo2, rating: 5) else { 63 fatalError("Unable to instantiate meal2") 64 } 65 66 guard let meal3 = Meal(name: "mesi3", photo: photo3, rating: 3) else { 67 fatalError("Unable to instantiate meal3") 68 } 69 70 meals += [meal1, meal2, meal3] 71 72 } 73 74} 75
この部分でエラーが発生しています。
swift
1 cell.nameLabel.text = meal.name 2 cell.photoImageView.image = meal.photo 3 cell.ratingControl.rating = meal.rating
nameLabel
, photo
, ratingControl
はOutlet接続はされています。
また、meal.name
, meal.photo
, meal.rating
の3つともnilではないため
代入先の変数がnilのためエラーが起きていると思われます。
原因はなんとなくわかるのですが、解決方法がわかりません。
よろしくお願いします。
##環境
xcode Version 10.2.1 (10E1001)
あなたの回答
tips
プレビュー