I am trying to play sounds in my project file, when a button is tapped.
Button is connected to a CollectionViewCell, which is repeating so I cannot create outlets on my ViewController.
Instead, I drop an action outlet to my ViewController to play sound when button is tapped.
let musicFile = Bundle.main.path(forResource: "\(soundNames["\(sender.currentTitle)"])", ofType: "mp3")
What I am trying to do here is; My buttons are already named according to the array I have created before, so if I can get the name of the button, that is certain that an .mp3 file is in my project and it will play.
But the line of code provided above gives me the error of:
Cannot subscript a value of type '[String]' with an index of type 'String'
How can I make this work? I can provided more code if necessary.
Thanks in advance.
Get rid of the "\(...)"
notation. You are not printing here; you are passing an actual string. Use actual values, directly, to form that string. This sort of thing would probably work:
let index = 0 // getting the _real_ number is the issue, perhaps
let title = soundNames[index]
let musicFile = Bundle.main.path(forResource: title, ofType: "mp3")
But really, it all depends on how soundNames
is constructed, which you have not shown.