简体   繁体   中英

How do I fix ,Unexpectedly found nil while unwrapping an Optional value, in my code

I am having trouble with my code everything was working fine and then I started to get this error

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

The error is occurring when I am letting my cell variable be a Reusable cell.

Here is my code, the error is occurring on line 3 where let cell is being declared.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let song = songs[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell") as! SongCell
    cell.setSong(song: song)
    return cell
}

Update: I have fixed the Fatal error but I am now getting

"Thread 1: signal SIGABRT"

The error is occurring when I add this code to set a table views data source and delegate.

override func viewDidLoad() {
            super.viewDidLoad()
            songs = createArray()
            playlists = createArray2()
            tableView.dataSource = self
            tableView.delegate = self
            tableView2.dataSource = self    //Adding this causes app to crash
            tableView2.delegate = self  //Adding this causes the app to crash

        // Do any additional setup after loading the view, typically from a nib.
    }  

Whenever I remove this code the app launches but no cells show in the table view.

You are missing the second argument of dequeueReusableCell

let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath) as! SongCell

Make sure to register a nib or class

tableView.register(UINib(nibName: "NibSongCell", bundle: nil), forCellReuseIdentifier: "SongCell")

OR

// if using a custom cell, replace UITableViewCell.self with that class
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SongCell")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM