条件绑定的初始值设定项必须具有可选类型,而不是"[String]"保护 在随机播放时



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

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

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()不返回可选,因此 linter 告诉您不要保护它,因为它没有任何意义。在这里阅读: https://developer.apple.com/documentation/swift/array/2994757-shuffled

let sound = sounds.shuffled()

这似乎也是错误的。let sound建议你只需要其中一个声音,shuffle 会返回声音数组 - 只是打乱。您可以做的是使用.first返回可选声音(可选,因为数组可能为空(。在这里阅读: https://developer.apple.com/documentation/swift/array/1689165-first

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

最新更新