Search code examples
iosswiftuiviewcontrollersegueuistoryboardsegue

Passing data from CollectionView to DetailVC in Swift 4


My CollectionView should pass a class model to DetailViewController, but when I tap on a cell I get the nil error.

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

The CollectionViewController is embedded programmatically on a TabBarController.

Collection View


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return soundArray.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SoundCell", for: indexPath) as? SoundCell {
    let SoundClass = soundArray[indexPath.row]
    cell.updateUI(SoundClass: SoundClass)
    return cell

    } else {
    return UICollectionViewCell()
    }
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    self.performSegue(withIdentifier: "seguetosound", sender: self)

  }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "seguetosound" {
    if let detailVC = segue.destination as? DetailSecondVC
    let sound = sender as? SoundClass { 
    detailVC.SoundClass = sound 

    }
 }

Detail View Controller

class DetailSecondVC: UIViewController, UIWebViewDelegate {

private var _SoundClass: SoundClass!

var SoundClass: SoundClass {
        get {
            return _SoundClass
        } set {
            _SoundClass = newValue
        }
    }

Do you know what I am missing here? I tested the segue with a simple white screen and it works but when I try to pass the data, it fails.


Solution

  • Edited: I thought the solution was to make the segue from the view controller instead of from the cell, but as matt said, the segue was correct from the cell but I just had to remove the implementation of didSelectItemAt