Swift 2 AVAudioRecorder Settings – Fix Ambiguous Without More Context Error

I was working on migrating the codebase of Yellr App from Swift 1.2 to Swift 2.0 and ran into this weird error that looks something like this:

Type of Expression is ambiguous without more context

This kind of error is generally thrown by XCode in Swift 2.0 when you do not specify the data types of the parameter values in various SDK property settings.

For, eg.

The settings dictionary I was using is this: (although it is correct but you cannot use it any more in Swift 2.0 on XCode 7)

var recordSettings = [
AVFormatIDKey: kAudioFormatAppleLossless,
AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
AVEncoderBitRateKey : 320000,
AVNumberOfChannelsKey: 2,
AVSampleRateKey : 44100.0
]

What you need to do instead is define the property values with their perfect datatypes. So, the new recordSettings dictionary should look something like this:

let recordSettings = [
AVSampleRateKey : NSNumber(float: Float(44100.0)),
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatAppleLossless)),
AVNumberOfChannelsKey : NSNumber(int: 1),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue)),
AVEncoderBitRateKey : NSNumber(int: Int32(320000))
]

As you can see above all the property values have been specified with the NSNumber datatype.

Now you can you this new recordSettings dictionary to initialize your AVAudioRecorder element as shown below:

var recorder: AVAudioRecorder!
do {
recorder = try AVAudioRecorder(URL: soundFileURL!, settings: recordSettings)
} catch var error as NSError {
recorder = nil
}

XCode should stop complaining after you make the change above. PLease let me know if this worked for you.

If this sounds like your situation, let's talk

No pitch decks. No sales process. Just a conversation about what you're dealing with and whether I can help.

Book a 30-minute call →