【问题标题】:Swift Dictionary Build errorSwift 字典构建错误
【发布时间】:2014-09-08 16:02:51
【问题描述】:

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

// 迅速

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

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

有人知道如何纠正吗?谢了

【问题讨论】:

  • 错误信息有误导性,使用NSNumber.numberWithInt(Int32(AVAudioQuality.Max.toRaw()))

标签: dictionary compiler-errors swift ios8


【解决方案1】:

您的 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];

【讨论】:

  • 啊,谢谢你 :) 我明天试试,然后标记你的答案!
  • 非常感谢!简单的解决方案!我唯一需要更改的是 AVFormatIDKey 并使用了您的第一个解决方案AVFormatIDKey : NSNumber(int: Int32(kAudioFormatAppleLossless))
  • @GerritPost:不客气。 kAudioFormatAppleLossless 的类型在 Swift 2 中发生了变化,比较 stackoverflow.com/questions/32509565/…
猜你喜欢
  • 1970-01-01
  • 2018-06-10
  • 2016-08-01
  • 1970-01-01
  • 2020-04-20
  • 1970-01-01
  • 2014-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多