fatal error: unexpectedly found nil while unwrapping an Optional value when AVFoundation Value of option type 'String? with UICollectionViewCell selection Swift 3.0
import UIKit
import AVFoundation
class ConsonantsVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate, AVAudioPlayerDelegate
{
let reuseIdentifier = "myCell"
var sounds: [String] = []
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
sounds = ["a", "b", "c", "d", "e"]
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
do
{
let audioPath = Bundle.main.path(forResource: sounds[indexPath.row], ofType: ".mp3")
try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch
{
print("ERROR")
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}