如何在 Swift 中将元素附加到字典中? [英] How to append elements into a dictionary in Swift?

查看:109
本文介绍了如何在 Swift 中将元素附加到字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的字典,其定义如下:

I have a simple Dictionary which is defined like:

var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]

现在我想在这个字典中添加一个元素:3 : "efg"

Now I want to add an element into this dictionary: 3 : "efg"

如何将 3 : "efg" 附加到现有字典中?

How can I append 3 : "efg" into this existing dictionary?

推荐答案

您正在使用 NSDictionary.除非你出于某种原因明确需要它是那种类型,否则我建议使用 Swift 字典.

You're using NSDictionary. Unless you explicitly need it to be that type for some reason, I recommend using a Swift dictionary.

您可以将 Swift 字典传递给任何需要 NSDictionary 的函数,而无需任何额外的工作,因为 Dictionary<>NSDictionary 无缝桥接到彼此.Swift 原生方式的优点是字典使用了泛型类型,所以如果你用 Int 为键,String 为值来定义它,就不会误用键和不同类型的值.(编译器代表您检查类型.)

You can pass a Swift dictionary to any function expecting NSDictionary without any extra work, because Dictionary<> and NSDictionary seamlessly bridge to each other. The advantage of the native Swift way is that the dictionary uses generic types, so if you define it with Int as the key and String as the value, you cannot mistakenly use keys and values of different types. (The compiler checks the types on your behalf.)

根据我在您的代码中看到的内容,您的字典使用 Int 作为键和 String 作为值.要创建实例并稍后添加项目,您可以使用以下代码:

Based on what I see in your code, your dictionary uses Int as the key and String as the value. To create an instance and add an item at a later time you can use this code:

var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"

如果您以后需要将其分配给 NSDictionary 类型的变量,只需进行显式转换:

If you later need to assign it to a variable of NSDictionary type, just do an explicit cast:

let nsDict = dict as! NSDictionary

而且,如前所述,如果您想将其传递给需要 NSDictionary 的函数,请按原样传递它,无需任何强制转换或转换.

And, as mentioned earlier, if you want to pass it to a function expecting NSDictionary, pass it as-is without any cast or conversion.

这篇关于如何在 Swift 中将元素附加到字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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