Search code examples
iosswiftxcodeoptional-values

Array declared for collectionview null value optional


I created an array that is my data for my collection view. I am attempting to tap on the CollectionViewCell and play the sound contained in the file component of my array. I dont't know how to play the sound and can't even get started because I get a null value for the files, which are in my xcode project.

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

If I don't force unwrap the file it gives me an error...

class ViewController: UIViewController {

let sounds : [Sounds] = [Sounds(statement: "A", file: Bundle.main.url(forResource: "A", withExtension: "aifc")!),
                            Sounds(statement: "B", file: Bundle.main.url(forResource: "B", withExtension: "aifc")!),
                            Sounds(statement: "C", file: Bundle.main.url(forResource: "C", withExtension: "aifc")!),
                            Sounds(statement: "D", file: Bundle.main.url(forResource: "D", withExtension: "aifc")!)]

}

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sounds.count
    }

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "soundCell", for: indexPath) as! CollectionViewCell
        let Soundz = sounds[indexPath.item]
        cell.cellLabel.text = Soundz.statement

        return cell
    }

}

struct Sounds{
    var statement : String
    var file : URL 
}


Solution

  • Looks like your files isn`t attached to the project. Check bundle resources and targets for attached files. And in this case better to use 'lazy var' instead of 'let'