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

泄露秘密 提交于 2019-12-11 08:20:49

问题


I am trying to migrate the next code from Objetive-C to 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];
    }

And I did the following:

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
}

and I am getting the following error:

error: type 'AnyObject' does not conform to protocol 'NSCopying' dictionary[code]=name

I don’t know how to declare the dictionary object, to do something as simple as an array with country codes strings as key and a small description. like

dictionary[“es-ES"]=[“Spanish”] dictionary[“en-US"]=[“American English”]


回答1:


NSDictionary keys need to conform to NSCopying, but AnyObject doesn't necessarily. (NSArray returns AnyObjects in Swift.) Use the as! operator on your code variable to be sure that it is:

dictionary[code as! NSCopying] = name

You can also downcast the language array to [String] and avoid the cast in the assignment code.



来源:https://stackoverflow.com/questions/28610516/swift-dictionary-population-issue-type-anyobject-does-not-conform-to-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!