简体   繁体   中英

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

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”]

NSDictionary keys need to conform to NSCopying , but AnyObject doesn't necessarily. ( NSArray returns AnyObject s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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