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'
有人知道如何纠正这个问题吗?谢谢
您的Swift代码中存在多个错误.
键和值的顺序是错误的.在dictionaryWithObjectsAndKeys
,键前面的值.但是Swift字典被写成了
[ key1 : value1, key2 : value2, ... ]
Run Code Online (Sandbox Code Playgroud)在NSNumber
初始化被映射到斯威夫特
NSNumber(float: ...), NSNumber(int: ...)
Run Code Online (Sandbox Code Playgroud)AVAudioQuality.Max
是一个enum
.要获得基础整数值,您必须使用.rawValue
.
这给了
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)