I'm dealing with an optional that I don't really want to have to deal with, but think do, catch
might be able to handle.
do { run(playSound["correct"]!) } catch {print("Failed to find")}
for those not familiar with SpriteKit, playsound("correct") is an action which plays a sound:
I create a lot of them, with a function, and put them in a dictionary where a string key is used to find the right one.
func makePlayable(_ soundFileName: String) -> SKAction {
let playSoundAction = SKAction.playSoundFileNamed(soundFileName, waitForCompletion: false)
return playSoundAction
}
... imagine a for
loop here punting a hundred or so of these into a dictionary with a string taken from the file name of the audio to act as key for the action that plays the appropriate sound.
The problem I'm wanting to deal with is that the use of a dictionary to return and play the actions means an optional is coming back.
Which needs unwrapping:
run(playSound["correct"]!)
Perhaps my fears are unfounded, but this instantly made me think I have to somehow do this more gracefully so I can deal with potential failure in the system that's trying to determine the string of the action of the sound file to play... yeah, sorry about that sentence.
The first choice I had was this:
if let soundAction = playSound["correct"]{
run(soundAction)
}
else{ print("Can't find playable sound Action with this name in \(playSound) dictionary")
}
This struck me as needless and long winded, so I looked at do
But that, when used in the way described at the top of the question, causes a warning indicating the catch is never going to get called.
What am I doing wrong, or am I wrongheaded in thinking do, catch
is even appropriate for this?