1
votes

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

1 Answers

7
votes

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.