【发布时间】:2020-01-21 03:07:20
【问题描述】:
我正处于编码的第一周。 到目前为止,我在 swift 中制作的 youtube 教程应用程序与上述错误消息完全不同。这是代码。我现在完全按照他们的规定重写了两次。 我正在尝试设置声音以与我们正在制作的纸牌游戏一起玩,当纸牌被洗牌、转身、匹配或不正确匹配时播放的声音。 错误消息显示为“let soundURL”代码行,“'return' 之后的代码将永远不会被执行”。 请帮忙?
class SoundManager {
static var audioPlayer:AVAudioPlayer?
enum SoundEffect {
case flip
case shuffle
case match
case nomatch
}
static func playSound(_ effect:SoundEffect) {
var soundFilename = ""
// Determine which sound effect we want to play
//and set the appropriate file name
switch effect {
case .flip:
soundFilename = "cardflip"
case .shuffle:
soundFilename = "cardflip"
case .match:
soundFilename = "dingcorrect"
case.nomatch:
soundFilename = "dingwrong"
}
// Get the path to the sound file inside the bundle
let bundlePath = Bundle.main.path(forResource: soundFilename, ofType: "wav")
guard bundlePath != nil else {
print("Couldn't find sound file \(soundFilename) in the bundle")
return
// Create a URL object from this string path
let soundURL = URL(fileURLWithPath: bundlePath!)
do {
// Create audio player object
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
// Play the sound
audioPlayer?.play()
}
catch {
// Could'nt create audio player object, log the error
print("Could'nt create the audio player object for sound file \(soundFilename)")
}
}
}
}
【问题讨论】:
-
在您的代码中的某处,您有
return关键字(大概在您提供的第一行代码的上方)。正如错误提示的那样,一旦出现 return 关键字,应用程序将退出该方法,因此return关键字以下的任何代码都不会执行。你能包含有这个return关键字的代码吗? -
嘿,大卫,我在上面添加了代码,将其复制到这里看起来很糟糕且不可读。我想知道为什么我的教程告诉我在它不起作用时添加 return。
-
看
guard bundlePath != nil else {,return下面的所有代码都不会被执行。我认为您需要在return之后放置一个},但您可能还需要删除一个
标签: ios swift iphone url avaudioplayer