如何动态地在swift字典中添加值 [英] How to add values in swift dictionary dynamically

查看:143
本文介绍了如何动态地在swift字典中添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在swift类中声明了一个字典如下:

I have declared a dictionary in my swift class as below :

var profileDetail = Dictionary< String,String>()

但是我无法在其中添加值。
如果我尝试跟随它,它只存储最后一个值。

But I'm not able to add values in it. IF I try like following, It only stores the last value.

profileDetail = [profileItem[1]:values.valueForKey("middle_name") as String]
profileDetail = [profileItem[2]:values.valueForKey("last_name") as String]
profileDetail = [profileItem[3]:values.valueForKey("gender") as String]
profileDetail = [profileItem[4]:values.valueForKey("birth_date") as String]
profileDetail = [profileItem[5]:"\(add1),\(add2)"]
profileDetail = [profileItem[6]:values.valueForKey("email") as String]






或以下给我错误的关键例外:


Or following gives me incorrect key exception:

ProfileDetail.setValue(values.valueForKey("first_name") as String, forKey: profileItem[0])
ProfileDetail.setValue(values.valueForKey("middle_name") as String, forKey: profileItem[1])
ProfileDetail.setValue(values.valueForKey("last_name") as String, forKey: profileItem[2])
ProfileDetail.setValue(values.valueForKey("gender") as String, forKey: profileItem[3])
ProfileDetail.setValue(values.valueForKey("birth_date") as String, forKey: profileItem[4])
ProfileDetail.setValue("\(add1),\(add2)", forKey: profileItem[5])
ProfileDetail.setValue(values.valueForKey("email") as String, forKey: profileItem[5]) 

我审阅了苹果的文档,但没有找到任何有用的东西。
动态地在 Dictionary 中添加值的正确方法是什么?

I refereed apple's doc but didn't find anything useful. What is the correct way of adding values in Dictionary dynamically ?

推荐答案

在这一行中你要实例化一个字典:

In this line you're instantiating a dictionary:

var profileDetail =  Dictionary<String, String>()

已识别通过 profileDetail 变量,但在所有其他后续行中,您将该变量重新分配给其他内容。也许这更好地解释了你所犯的错误:

identified by the profileDetail variable, but in all other subsequent lines you keep reassigning that variable to something else. Maybe this better explains the error you're making:

var x: Int = 1
x = 2
x = 3
x = 4

每一行都为同一个变量赋予一个新值,所以之前的值已丢失。

Each line assigns a new value to the same variable, so the previous value is lost.

我认为您应该用以下内容替换每一行:

I think you should replace each of those lines with something like:

profileDetail[profileItem[1]] = values.valueForKey("middle_name") as String

甚至更好,你可以在一个语句中初始化如下:

or even better you can initialize in a single statement as follows:

var profileDetail = [
    profileItem[1]: values.valueForKey("middle_name"),
    profileItem[2]: values.valueForKey("last_name"),
    ...
]

您还可以将 var 更改为如果这个字典一旦实例化,就不应该被修改

You can also change var to let if this dictionary, once instantiated, is not supposed to be modified

这篇关于如何动态地在swift字典中添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆