Royalty Club Royalty Club - 2 months ago 32
iOS Question

Swift / Spring - Ambiguous reference to member 'subscript'

My 2nd question on here and it's Spring related yet again, your assistance is greatly appreciated.

Here is the line of code that receives the issue code:

var soundID : SystemSoundID = Internal.cache[url] ?? 0


and

Internal.cache[url] = soundID


Issue Code:

Ambiguous reference to member 'subscript'


Additional Code:

struct SoundPlayer {

static var filename : String?
static var enabled : Bool = true

private struct Internal {
static var cache = [NSURL:SystemSoundID]()
}

static func playSound(soundFile: String) {

if !enabled {
return
}

if let url = Bundle.main.url(forResource: soundFile, withExtension: nil) {

var soundID : SystemSoundID = Internal.cache[url] ?? 0

if soundID == 0 {
AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
Internal.cache[url] = soundID
}

AudioServicesPlaySystemSound(soundID)

} else {
print("Could not find sound file name `\(soundFile)`")
}
}

static func play(file: String) {
self.playSound(soundFile: file)
}


}

Answer

The cache directory is defined as

static var cache = [NSURL: SystemSoundID]()

i.e. the key is of the type NSURL. But Bundle.main.url(...) returns a URL, which is the "corresponding" value type. You can either bridge from URL to NSURL:

 var soundID = Internal.cache[url as NSURL] ?? 0

or (and that appears to me as the better solution), change the dictionary definition to

static var cache = [URL: SystemSoundID]()