Swift Dictionary Build错误

CPl*_*lus 2 dictionary compiler-errors swift ios8

我试着将这个obj-c代码翻译成swift代码:

NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
                              [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                              [NSNumber numberWithInt: 2],                         AVNumberOfChannelsKey,
                              [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                              nil];
Run Code Online (Sandbox Code Playgroud)

//很快

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

但我收到错误:Type()不符合协议'FloatLiteralConvertible'

有人知道如何纠正这个问题吗?谢谢

Mar*_*n R 5

您的Swift代码中存在多个错误.

这给了

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

但是NSNumber如果需要,数字会自动包装到对象中,因此您可以将其简化为

var settings : [NSString : NSNumber ] = [AVSampleRateKey : 44100.0,
    AVFormatIDKey : kAudioFormatAppleLossless,
    AVNumberOfChannelsKey : 2,
    AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue];
Run Code Online (Sandbox Code Playgroud)

斯威夫特2,类型kAudioFormatAppleLossless更改为Int32这是桥接NSNumber自动,所以你必须要改变这

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