objective-c - swift字典人口问题: type 'AnyObject' does not conform to protocol 'NSCopying'

标签 objective-c arrays swift dictionary declaration

我正在尝试将下一个代码从 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];
    }

我做了以下事情:

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”不符合协议(protocol)“NSCopying” dictionary[code]=name

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

字典[“es-ES”]=[“西类牙语”] dictionary[“en-US”]=[“美式英语”]

最佳答案

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

dictionary[code as! NSCopying] = name

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

关于objective-c - swift字典人口问题: type 'AnyObject' does not conform to protocol 'NSCopying' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28610516/

相关文章:

iphone - 从 HTTP Live Streaming 播放视频时访问 AVPlayer 的数据

ios - 如何在 Objective-C/iOS 中的客户端上创建虚拟 JSON 数据?

C# Byte[] 到 BCD 和 BCD 到 INT

java 嵌套 JSONArray

ios - 如何执行 whereKey 以便查询距当前用户____公里远的帖子?

ios - 过渡时启动键盘动画

ios - 应用程序在 iOS5 模拟器和分析器上崩溃

iphone - 在我的主视图中将 UIImageView 置于其他 UIImageView 之上

javascript - Protractor 断言数组的每个元素都小于 500

ios - 如何快速访问嵌套 JSON 中的数据