繁体   English   中英

快速字典填充问题:类型“ AnyObject”不符合协议“ NSCopying”

[英]swift dictionary population issue: type 'AnyObject' does not conform to protocol 'NSCopying'

我正在尝试将下一个代码从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”字典[code] = name

我不知道如何声明字典对象,如何像将国家代码字符串作为键和简短描述那样简单地执行数组操作。 喜欢

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

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

dictionary[code as! NSCopying] = name

您还可以将language数组转换为[String]并避免在分配代码中进行强制转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM