swift3 - Nil Error While Running -
i working on todo app,it completed , running begins give error "fatal error: unexpectedly found nil while unwrapping optional value".need guide!
class viewcontroller: uiviewcontroller, uitableviewdatasource, uitableviewdelegate{ @iboutlet weak var tableview: uitableview! var tasks : [task] = [ ] override func viewdidload() { super.viewdidload() tableview.datasource = self tableview.delegate = self // additional setup after loading view, typically nib. } override func viewwillappear(_ animated: bool) { getdata() tableview.reloaddata() } func tableview(_ tableview: uitableview, numberofrowsinsection section: int) -> int { return tasks.count } func tableview(_ tableview: uitableview, cellforrowat indexpath: indexpath) -> uitableviewcell { let cell = uitableviewcell() let task = tasks[indexpath.row] if task.isimportant{ cell.textlabel?.text = " ★ \(task.name!)" }else{ cell.textlabel?.text = task.name! } return cell } func getdata() { let context = (uiapplication.shared.delegate as! appdelegate).persistentcontainer.viewcontext do{ tasks = try context.fetch(task.fetchrequest()) } catch { print ("failed!") } }
}
you should avoid unwrapping optionals !
because of danger of encountering runtime error if optional missing. try following:
let taskname = task.name ?? "no name" if task.isimportant{ cell.textlabel?.text = " ★ \(taskname)" }else{ cell.textlabel?.text = taskname }
Comments
Post a Comment