swift字典填充问题:类型'AnyObject'不符合协议'NSCopying'

mar*_*osm 1 arrays dictionary declaration objective-c swift

我正在尝试将下一个代码从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];
    }
Run Code Online (Sandbox Code Playgroud)

我做了以下事情:

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
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

错误:类型'AnyObject'不符合协议'NSCopying'字典[code] = name

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

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

zne*_*eak 7

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

dictionary[code as! NSCopying] = name
Run Code Online (Sandbox Code Playgroud)

您还可以向下转换language数组[String]并避免在赋值代码中进行强制转换.