CPlusPlus
CPlusPlus

Reputation: 479

Swift Dictionary Build error

I tried to do translate this obj-c code to swift code:

NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
                              [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                              [NSNumber numberWithInt: 2],                         AVNumberOfChannelsKey,
                              [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                              nil];

// swift

    var settings = [NSNumber.numberWithFloat(Float(44100.0)): AVSampleRateKey,
            NSNumber.numberWithInt(Int32(kAudioFormatAppleLossless)): AVFormatIDKey,
            NSNumber.numberWithInt(2): AVNumberOfChannelsKey,
            NSNumber.numberWithInt(Int32(AVAudioQuality.Max)): AVEncoderAudioQualityKey];

But I get the error: Type () does not conform to protocol 'FloatLiteralConvertible'

Does anybody know how to correct this? THX

Upvotes: 2

Views: 2539

Answers (1)

Martin R
Martin R

Reputation: 539705

There are several errors in your Swift code.

  • The order of keys and values is wrong. In dictionaryWithObjectsAndKeys, the values precede the keys. But a Swift dictionary is written as

    [ key1 : value1, key2 : value2, ... ]
    
  • The NSNumber initializers are mapped to Swift as

    NSNumber(float: ...), NSNumber(int: ...)
    
  • AVAudioQuality.Max is an enum. To get the underlying integer value, you have to use .rawValue.

This gives

var settings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
    AVFormatIDKey : NSNumber(int: Int32(kAudioFormatAppleLossless)),
    AVNumberOfChannelsKey : NSNumber(int: 2),
    AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Max.rawValue))];

But numbers are automatically wrapped into NSNumber objects if necessary, so you can simplify that to

var settings : [NSString : NSNumber ] = [AVSampleRateKey : 44100.0,
    AVFormatIDKey : kAudioFormatAppleLossless,
    AVNumberOfChannelsKey : 2,
    AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue];

In Swift 2, the type of kAudioFormatAppleLossless changed to Int32 which is not bridged to NSNumber automatically, so you have to change this to

var settings : [NSString : NSNumber ] = [AVSampleRateKey : 44100.0,
    AVFormatIDKey : Int(kAudioFormatAppleLossless),
    AVNumberOfChannelsKey : 2,
    AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue];

Upvotes: 6

Related Questions