gpt4 book ai didi

dictionary - Swift 字典构建错误

转载 作者:可可西里 更新时间:2023-11-01 00:38:18 24 4
gpt4 key购买 nike

我尝试将此 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];

// swift

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

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

有人知道怎么解决吗?谢谢

最佳答案

您的 Swift 代码中有几个错误。

  • 键和值的顺序错误。在 dictionaryWithObjectsAndKeys 中,值在键之前。但是 Swift 字典写成

    [ key1 : value1, key2 : value2, ... ]
  • NSNumber 初始化器映射到 Swift 为

    NSNumber(float: ...), NSNumber(int: ...)
  • 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))];

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

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

Swift 2 中,kAudioFormatAppleLossless 的类型更改为 Int32桥接到 NSNumber 自动,所以你必须将其更改为

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

关于dictionary - Swift 字典构建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25728372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com