[英]swift dictionary population issue: type 'AnyObject' does not conform to protocol 'NSCopying'
我正在嘗試將下一個代碼從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”不符合協議“ NSCopying”字典[code] = name
我不知道如何聲明字典對象,如何像將國家代碼字符串作為鍵和簡短描述那樣簡單地執行數組操作。 喜歡
字典[“ es-ES”] = [“西班牙文”]字典[“ en-US”] = [“美國英語”]
NSDictionary
鍵需要符合NSCopying
,但AnyObject
不一定。 ( NSArray
在Swift中返回AnyObject
。)使用as!
您的code
變量上的運算符,以確保它是:
dictionary[code as! NSCopying] = name
您還可以將language
數組轉換為[String]
並避免在分配代碼中進行強制轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.