Reputation: 33
Morning
Im working through one of the Udemy AppBrewer courses and I've been looking at how I would solve one of the pieces of work. Ive done what I felt was logical but its returning an error.
Using Swift Im trying to play one of two sounds based on a button being pressed using the the tag value to define the sound to be played. The code works when I don't have any condition created.
Im trying to use an IF statement to review the tag value and then make a decision.
My problem is that I get a 'Use of unresolved identifier' which on review sounds like it doesnt understand one of my variables ( the one in the condition). I cant understand why this would be the case and I dont have enough knowledge on swift to disect it
Works out of the condition just not when Ive put in an IF statement
@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()
}
}
This is the error code:
Error Use of Unresolved identifier "soundURL" "catch" block is unreachable because no errors are thrown into the Do Block
(not sure why my code format is so off)
Upvotes: 3
Views: 55
Reputation: 271625
Because the soundURL
variable is declared inside the if
and else
branches. The do
block is out of the if
statement, so soundURL
is out of scope in the do
block, which is why the compiler can't "see" it.
To fix it, declare soundURL
outside of the if
statement:
let soundURL: URL?
if sender.tag == 1 {
soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav")
}
else {
soundURL = Bundle.main.url(forResource: "note2", withExtension: "wav")
}
Now soundURL
is in the same scope as the do
block.
Upvotes: 1