【问题标题】:Cannot convert value of type `[String: String?]` to expected argument type `[String: String!]`无法将 `[String: String?]` 类型的值转换为预期的参数类型 `[String: String!]`
【发布时间】:2016-01-14 20:09:14
【问题描述】:

您好,我在向字典附加值时遇到错误。我正在使用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)
    }

感谢任何帮助。

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

【问题讨论】:

  • 查看我编辑的问题

标签: ios swift dictionary swift2 avspeechsynthesizer


【解决方案1】:

也许你的 arrVoiceLanguages 变量声明了 [String:String!] 类型并且 NSLocale.currentLocale().displayNameForKey() 函数的返回类型是 String?。

所以你可以试试这个(我在末尾添加了 ! 来展开值)。

let languageName = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: voiceLanguageCode)!

【讨论】:

    【解决方案2】:

    您的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)
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2015-12-24
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多