嗨我在向dictornary追加价值时遇到错误。我正在使用Xcode 7
和Swift 2
。
错误消息:无法将[String: String?]
类型的值转换为预期的参数类型[String: String!]
声明:
var arrVoiceLanguages: [Dictionary<String, String!>] = []
以下是我的功能
for voice in AVSpeechSynthesisVoice.speechVoices() {
let voiceLanguageCode = (voice as AVSpeechSynthesisVoice).language
let languageName = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: voiceLanguageCode)
let dictionary = ["languageName": languageName, "languageCode": voiceLanguageCode]
arrVoiceLanguages.append(dictionary)
}
感谢任何帮助。
我不知道人们为什么放弃对这个问题的投票。!
答案 0 :(得分:2)
也许你的arrVoiceLanguages变量声明了[String:String!]类型和NSLocale.currentLocale()。displayNameForKey()函数的返回类型是String?。
所以你可以尝试这个(我添加了!最后解开值)。
let languageName = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: voiceLanguageCode)!
答案 1 :(得分:1)
您的arrVoiceLanguages
数组类型应为:
var arrVoiceLanguages = [[String: String?]]()
或者您需要以这种方式解开languageName
:
guard let languageName = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: voiceLanguageCode) else {return}
因为NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: voiceLanguageCode)
返回可选字符串。
通过展开languageName
,您不需要更改arrVoiceLanguages
数组的类型。你的代码将是:
var arrVoiceLanguages: [Dictionary<String, String!>] = []
for voice in AVSpeechSynthesisVoice.speechVoices() {
let voiceLanguageCode = (voice as AVSpeechSynthesisVoice).language
guard let languageName = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: voiceLanguageCode) else {return}
let dictionary = ["languageName": languageName, "languageCode": voiceLanguageCode]
arrVoiceLanguages.append(dictionary)
}