无法将`[String:String?]`类型的值转换为预期的参数类型`[String:String!]`

时间:2015-10-16 06:56:08

标签: ios swift dictionary swift2 avspeechsynthesizer

嗨我在向dictornary追加价值时遇到错误。我正在使用Xcode 7Swift 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)
    }

感谢任何帮助。

我不知道人们为什么放弃对这个问题的投票。!

2 个答案:

答案 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)
    }