迅速字典人口问题:类型AnyObject“不符合协议”NSCopying“ [英] swift dictionary population issue: type 'AnyObject' does not conform to protocol 'NSCopying'

查看:163
本文介绍了迅速字典人口问题:类型AnyObject“不符合协议”NSCopying“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从迁移Objetive-C斯威夫特下一个code:

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];
    }

和我做了以下内容:

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 =名称

我不知道如何申报字典对象,做与国家codeS字符串作为键和一个小的描述数组一样简单。

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

词典[ES-ES] = [西班牙]
   词典[EN-US] = [美国英语]

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

推荐答案

的NSDictionary 键需要符合 NSCopying ,但 AnyObject 不一定。 (的NSArray 收益 AnyObject S IN斯威夫特)使用为<!/ code>在 code 变量运营商,以确保它是:

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

您也可以向下转换的语言阵列 [字符串] ,并避免在分配$ C $投C。

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

这篇关于迅速字典人口问题:类型AnyObject“不符合协议”NSCopying“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆