条件绑定的初始值设定项必须具有 Optional 类型,而不是 '[String]' guard let when shuffled

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

我遇到了随机播放声音的问题。当我得到 guard let sound = sounds.shuffled(), 时,它给我一个错误 Initializer for conditional binding must have Optional type, not '[String]'

知道如何解决这个问题吗?是因为guard let吗?这是我的代码:

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()

我想你是想用

guard let sound = sounds.first

从打乱后的数组中选出第一个元素(如果数组为空,则可以为 nil)。

或者您可以删除随机播放,只使用

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

sounds.shuffled() 不是 return 可选的,因此 linter 会告诉您不要保护它,因为它没有任何意义。在这里阅读:https://developer.apple.com/documentation/swift/array/2994757-shuffled

let sound = sounds.shuffled()

这似乎也是错误的。 let sound 建议您只需要其中一种声音,随机播放 return 声音数组 - 只是随机播放。您可以做的是在可选声音上使用 .first which returns(可选,因为数组可能为空)。阅读此处:https://developer.apple.com/documentation/swift/array/1689165-first

guard let sound = sound.first, ... else { return }