在if语句中使用未解决的标识符



早上

我正在通过一门Udemy Appbrewer课程进行工作,我一直在研究如何解决其中一项工作。我做了我认为合乎逻辑的事情,但它返回错误。

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

我试图使用if语句来查看标签值,然后做出决定。

我的问题是我获得了"使用未解决的标识符",这听起来听起来好像不了解我的一个变量(条件下的变量(。我不明白为什么会这样,而且我对Swift没有足够的知识来消除它

当Ive放入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()
}
}

这是错误代码:

错误使用未解决的标识符" soundurl" "捕获"块是无法到达的,因为没有任何错误被扔进do块

(不确定为什么我的代码格式如此关闭(

因为soundURL变量在ifelse分支中声明。do块不含if语句,因此soundURLdo块中 ,这就是为什么编译器无法"看到"它的原因。

要修复它,请在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块相同的范围。

最新更新