【问题标题】:How to create and add values to Dictionary in swift如何在 swift 中创建和添加值到字典
【发布时间】:2015-08-24 16:43:28
【问题描述】:

我想用不同类型的数据(数组,字符串,字典)快速创建一个字典 这是字典的 json

{
  "GenInfo": {
    "First Name":"Varun",
    "Last Name":"Naharia",
    "Phone No":"123456789"
  },
  "LangInfo": ["Hindi","English","Urdu","French"],
  "EduInfo": 
    [
      {
        "Collage":"CIITM",
        "Year":"2009",
        "Degree":"BCA"
      },
      {
        "Collage":"Dept. Of Comp. Sci. & Infor. University Of Kota",
        "Year":"2013",
        "Degree":"MCA"
      }
    ]
}

我想将这些值一个一个地添加到字典中,例如首先是 GenInfo,然后是 LangInfo 的第一种语言,然后是 EduInfo

朗信息

教育资讯

我使用dict["GenInfo"] = ["FirstName":first,"LastName":last,"Phone":phone] 在 dic 中添加 GenInfo,其中 first 和 last 是具有值的变量。

编辑 #1 var dict = Dictionary<String, Any>()

【问题讨论】:

  • 你能证明你定义字典吗?如果您使用let 来定义它,那么字典将不会是可变的。您应该使用 var 使该 Dictionary 可变。
  • 是的,它是 var,我已经添加了 GenInfo,但是在 LangInfo 中一一添加数组值时遇到问题
  • 好的,你能把代码贴在你试图附加 LangInfo 的地方吗?
  • dict["Language"]=[lang]
  • LangData 的 'data' 属性是否也使用 'var' 定义?

标签: ios swift dictionary


【解决方案1】:

这是一个已知问题,显然尚未修复(请参阅Is it possible to have a dictionary with a mutable array as the value in Swift

解决方法是使用您的数组创建一个新变量,然后将其分配回去:

    var dict = [String: AnyObject]()
    dict["GenInfo"] = ["FirstName":"first","LastName":"last","Phone":"phone"]
    dict["Language"] = ["langage1", "langage2"]

    if var languages = dict["Language"] as? [String] {
        languages.append("langage3")
        dict["Language"] = languages
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2015-01-05
    相关资源
    最近更新 更多