无法将类型`[String:String?]`的值转换为期望的参数类型`[String:String!]'
问题描述:
您好,我在将值附加到dictornary时出错。我正在使用Xcode 7
和Swift 2
。 错误消息:不能[String: String?]
类型的值转换为预期的参数类型[String: String!]
无法将类型`[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)
}
任何帮助表示赞赏。
我不知道为什么人们对这个问题放弃投票。
答
你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)
}
答
也许你arrVoiceLanguages变量声明[字符串:字符串!]类型和NSLocale.currentLocale()displayNameForKey()函数的返回类型为String?。
所以你可以尝试这个(我加了!在结束打开价值)。
let languageName = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: voiceLanguageCode)!
+0
是的..这对我很有用。谢谢。 –
看到我编辑的问题 –