【问题标题】:swift dictionary population issue: type 'AnyObject' does not conform to protocol 'NSCopying'快速字典填充问题:类型“AnyObject”不符合协议“NSCopying”
【发布时间】:2015-02-19 15:41:35
【问题描述】:

我正在尝试将下一个代码从 Objetive-C 迁移到 Swift:

   NSArray *voices = [AVSpeechSynthesisVoice speechVoices];
    NSArray *languages = [voices valueForKey:@"language"];

    NSLocale *currentLocale = [NSLocale autoupdatingCurrentLocale];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    for (NSString *code in languages)
    {
        dictionary[code] = [currentLocale displayNameForKey:NSLocaleIdentifier value:code];
    }

我做了以下事情:

var voices:NSArray = AVSpeechSynthesisVoice.speechVoices()
var languages:NSArray=voices.valueForKey("language") as NSArray

var currentLocale:NSLocale=NSLocale.autoupdatingCurrentLocale()
var dictionary:NSMutableDictionary=NSMutableDictionary()

for code in languages {
   var name=currentLocale.displayNameForKey(NSLocaleIdentifier, value: code)
   dictionary[code]=name
}

我收到以下错误:

错误:类型“AnyObject”不符合协议“NSCopying” 字典[代码]=名称

我不知道如何声明字典对象,做一些简单的事情,比如一个以国家代码字符串作为键和一个小描述的数组。 喜欢

字典[“es-ES”]=[“西班牙语”] 字典[“en-US”]=[“美式英语”]

【问题讨论】:

    标签: objective-c arrays swift dictionary declaration


    【解决方案1】:

    NSDictionary 键需要符合NSCopying,但AnyObject 不一定。 (NSArray 在 Swift 中返回 AnyObjects。)在您的 code 变量上使用 as! 运算符以确保它是:

    dictionary[code as! NSCopying] = name
    

    您还可以将language 数组向下转换为[String],并避免在赋值代码中进行转换。

    【讨论】:

    • 非常感谢,字典[code as! NSCopying]=name 返回错误“Expected , separator” 我在操场上测试这个,你只需要导入 AVFoundation 来测试。关于语言的沮丧,我想知道你是否可以帮助我,我从swift开始,我很迷茫。
    • 对不起,用作。作为!是 Swift 1.2 并且仅适用于 Xcode 6.3 及更高版本。
    • 正如您所暗示的,更好的解决方案是将语言数组向下转换为正确的类型,var languages = voices.valueForKey("language") as [String]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 2015-01-02
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多