gpt4 book ai didi

swift - 在 IF 语句中使用未解析的标识符

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:11 24 4
gpt4 key购买 nike

早上好

我正在学习 Udemy AppBrewer 类(class)之一,我一直在研究如何解决其中一项工作。我做了我认为合乎逻辑的事情,但它返回了一个错误。

我正在使用 Swift 尝试根据按下的按钮播放两种声音中的一种,使用标签值来定义要播放的声音。当我没有创建任何条件时,代码有效。

我正在尝试使用 IF 语句来查看标记值,然后做出决定。

我的问题是我得到一个“使用未解析的标识符”,在审查时听起来它不理解我的变量之一(条件中的那个)。我不明白为什么会这样,而且我对 swift 的了解不足,无法剖析它

在我放入 IF 语句时不符合条件

@IBAction func notePressed(_ sender: UIButton) 
{
if sender.tag == 1 {
let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav")
}
else {
let soundURL = Bundle.main.url(forResource: "note2", withExtension: "wav")
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}

audioPlayer.play()
}
}

这是错误代码:

Error Use of Unresolved identifier "soundURL" "catch" block is unreachable because no errors are thrown into the Do Block

(不知道为什么我的代码格式这么差)

最佳答案

因为 soundURL 变量是在 ifelse 分支中声明的。 do block 在 if 语句之外,因此 soundURLdo 中超出范围 block ,这就是编译器无法“看到”它的原因。

要修复它,请在 if 语句之外声明 soundURL:

let soundURL: URL?
if sender.tag == 1 {
soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav")
}
else {
soundURL = Bundle.main.url(forResource: "note2", withExtension: "wav")
}

现在 soundURLdo block 在同一范围内。

关于swift - 在 IF 语句中使用未解析的标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56088221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com