Search code examples
iosarraysswiftavaudioplayershuffle

Initializer for conditional binding must have Optional type, not '[String]' guard let when shuffled


I got problem with shuffling sounds. When I got guard let sound = sounds.shuffled(), it gets me an error Initializer for conditional binding must have Optional type, not '[String]'

Any idea how to fix this? Is it because of guard let? Here is my code:

var audioPlayer: AVAudioPlayer!

@IBAction func playButtonPressed(_ sender: UIButton) {
        let sounds = ["x", "y", "z"].shuffled()

        guard let sound = sounds.shuffled(),
        let soundURL = Bundle.main.url(forResource: sound, withExtension: "mp3") else { return }


        do {
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        }
        catch {
            print(error)
        }
            audioPlayer.play()

Solution

  • I think you meant to use

    guard let sound = sounds.first
    

    which picks the first element out of the shuffled array (which can be nil if the array is empty).

    Alternatively you can remove the shuffle and just use

    guard let sound = ["x", "y", "z"].randomElement()