티스토리 뷰

Swift & objc

swift fatalError

rhinoPHS 2018. 7. 6. 11:59


swift fatalError


코드에서 최대한 Force Unwrapping을 쓰지 않으려고 하다가 자주 쓰게 되는 fatalError
Force Unwrapping을 자주 썼던 곳은 dequeueReusableCell할 때다.

    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"

        

        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MealTableViewCell

        // Fetches the appropriate meal for the data source layout.

        

        let meal = meals[indexPath.row]

        cell.nameLabel.text = meal.name

        cell.photoImageView.image = meal.photo

        cell.ratingControl.rating = meal.rating


        return cell

    }



최근 부터는 fatalError를 쓴다

    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

        cell.photoImageView.image = meal.photo

        cell.ratingControl.rating = meal.rating


        return cell

    }


Force Unwrapping이나 fataError 둘다 앱이 죽기는 마찬가지지다. 다른 점은 개발자에게 문제의 원인을 명확하게 알려 줄 수 있다는 점이다. 



Force Unwrapping보다 나은 방법이긴 하지만 silver bullet은 아닌 것 같다.

관련글 링크s







반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함