为 collectionview 声明的数组 null 值可选

Array declared for collectionview null value optional

我创建了一个数组,它是我的集合视图的数据。 我试图点击 CollectionViewCell 并播放我的数组的文件组件中包含的声音。我不知道如何播放声音,甚至无法开始,因为我的 xcode 项目中的文件的值为空值。

错误:线程 1:致命错误:在展开可选值时意外发现 nil

如果我不强制解包文件,它会给我一个错误...

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 
}

首先,当您试图将 URL 写入您的文件时,您不应该在您的声音阵列中强制解包 !。这导致了崩溃。你应该选一个 URL.

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


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"))]

}

这将首先解决崩溃问题。当您访问要播放的文件时,请先检查 URL 是否存在或为零。

其次,确保所有声音文件都已添加到 Target。检查文件的 属性-inspector 并确保选中您的应用程序目标复选框。

您的文件似乎没有附加到项目中。检查附加文件的捆绑资源和目标。在这种情况下,最好使用 'lazy var' 而不是 'let'

Don't Keep Bundle.main.url(forResource: "", withExtension: "") in an Array as if Array size will increase, this statement will take a lot of memory.

Instead of your approach, Keep fileName in your object and when you need path of that file, just call filePath instance variable of your object.

 let sounds = [Sounds(statement: "A", fileName: "A")]

您的结构将如下所示

struct Sounds {
    var statement : String
    var fileName: String
    var filePath : URL? {
        return Bundle.main.url(forResource: fileName, withExtension: "html")
    }
}

希望对您有所帮助。