ios Swift:声明一个空字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24033393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: declare an empty dictionary
提问by z22
I am beginning to learn swift
by following the iBook-The Swift Programming Language
on Swift provided by Apple. The book says to create an empty dictionary one should use [:]
same as while declaring array as []
:
我开始学习Apple 提供swift
的 iBook- The Swift Programming Language
on Swift。这本书说要创建一个空字典,应该使用[:]
与将数组声明为相同的方法[]
:
I declared an empty array as follows :
我声明了一个空数组,如下所示:
let emptyArr = [] // or String[]()
But on declaring empty dictionary, I get syntax error:
但是在声明空字典时,我收到语法错误:
let emptyDict = [:]
How do I declare an empty dictionary?
如何声明一个空字典?
回答by damirstuhec
var emptyDictionary = [String: String]()
var populatedDictionary = ["key1": "value1", "key2": "value2"]
Note: if you are going to change the contents of the dictionary over time then declare it as a var
(variable). You candeclare an empty dictionary as a let
(constant) but it is pointless if you have the intention of changing its contents over time, since constant can't be changed after it has been initialized.
注意:如果您打算随时间更改字典的内容,请将其声明为var
(变量)。您可以将空字典声明为let
(常量),但如果您打算随时间更改其内容,则毫无意义,因为常量在初始化后无法更改。
Old answer:
旧答案:
Creating an empty dictionary of type <String, String>
would look as follows:
创建类型为空的字典<String, String>
如下所示:
var emptyDictionary = Dictionary<String, String>()
回答by Gabriele Petronella
You can't use [:]
unless type information is available.
[:]
除非类型信息可用,否则您不能使用。
You need to provide it explicitly in this case:
在这种情况下,您需要明确提供它:
var dict = Dictionary<String, String>()
var
means it's mutable, so you can add entries to it.
Conversely, if you make it a let
then you cannot further modify it (let
means constant).
var
意味着它是可变的,所以你可以向它添加条目。相反,如果您将其设为 a,let
则无法进一步修改它(let
表示常量)。
You can use the [:]
shorthand notation if the type information can be inferred, for instance
[:]
例如,如果可以推断类型信息,则可以使用速记符号
var dict = ["key": "value"]
// stuff
dict = [:] // ok, I'm done with it
In the last example the dictionary is known to have a type Dictionary<String, String>
by the first line. Note that you didn't have to specify it explicitly, but it has been inferred.
在最后一个例子中Dictionary<String, String>
,第一行就知道字典有一个类型。请注意,您不必明确指定它,但它已被推断出来。
回答by Suragch
The Swift documentationrecommends the following way to initialize an empty Dictionary:
在斯威夫特文档建议采取以下方法来初始化一个空字典:
var emptyDict = [String: String]()
I was a little confused when I first came across this question because different answers showed different ways to initialize an empty Dictionary. It turns out that there are actually a lot of ways you can do it, though some are a little redundant or overly verbose given Swift's ability to infer the type.
当我第一次遇到这个问题时,我有点困惑,因为不同的答案显示了初始化空字典的不同方法。事实证明,实际上有很多方法可以做到,尽管鉴于 Swift 推断类型的能力,有些方法有点多余或过于冗长。
var emptyDict = [String: String]()
var emptyDict = Dictionary<String, String>()
var emptyDict: [String: String] = [:]
var emptyDict: [String: String] = [String: String]()
var emptyDict: [String: String] = Dictionary<String, String>()
var emptyDict: Dictionary = [String: String]()
var emptyDict: Dictionary = Dictionary<String, String>()
var emptyDict: Dictionary<String, String> = [:]
var emptyDict: Dictionary<String, String> = [String: String]()
var emptyDict: Dictionary<String, String> = Dictionary<String, String>()
After you have an empty Dictionary you can add a key-value pair like this:
在你有一个空的 Dictionary 之后,你可以像这样添加一个键值对:
emptyDict["some key"] = "some value"
If you want to empty your dictionary again, you can do the following:
如果要再次清空字典,可以执行以下操作:
emptyDict = [:]
The types are still <String, String>
because that is how it was initialized.
类型仍然<String, String>
是因为它是如何初始化的。
回答by Lim Thye Chean
Use this will work.
使用这个会起作用。
var emptyDict = [String: String]()
回答by Jio
You can simply declare it like this:
你可以简单地像这样声明它:
var emptyDict:NSMutableDictionary = [:]
回答by nevan king
You have to give the dictionary a type
你必须给字典一个类型
// empty dict with Ints as keys and Strings as values
var namesOfIntegers = Dictionary<Int, String>()
If the compiler can infer the type, you can use the shorter syntax
如果编译器可以推断类型,则可以使用较短的语法
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String
回答by Juan Boero
Swift:
迅速:
var myDictionary = Dictionary<String, AnyObject>()
回答by Lorem Ipsum Dolor
You need to explicitly tell the data type or the type can be inferred when you declare anything in Swift.
当你在 Swift 中声明任何东西时,你需要明确地告诉数据类型或者类型可以被推断出来。
Swift 3
斯威夫特 3
The sample below declare a dictionary with key as a Int
type and the value as a String
type.
下面的示例声明了一个字典,键是Int
类型,值是String
类型。
Method 1: Initializer
方法一:初始化器
let dic = Dictionary<Int, String>()
Method 2: Shorthand Syntax
方法 2:速记语法
let dic = [Int:String]()
Method 3: Dictionary Literal
方法 3:字典字面量
var dic = [1: "Sample"]
// dic has NOT to be a constant
dic.removeAll()
回答by Shakeel Ahmed
Swift 4
斯威夫特 4
let dicc = NSDictionary()
//MARK: - This is empty dictionary
let dic = ["":""]
//MARK:- This is variable dic means if you want to put variable
let dic2 = ["":"", "":"", "":""]
//MARK:- Variable example
let dic3 = ["name":"Shakeel Ahmed", "imageurl":"https://abc?abc.abc/etc", "address":"Rawalpindi Pakistan"]
//MARK: - This is 2nd Variable Example dictionary
let dic4 = ["name": variablename, "city": variablecity, "zip": variablezip]
//MARK:- Dictionary String with Any Object
var dic5a = [String: String]()
//MARK:- Put values in dic
var dic5a = ["key1": "value", "key2":"value2", "key3":"value3"]
var dic5b = [String:AnyObject]()
dic5b = ["name": fullname, "imageurl": imgurl, "language": imgurl] as [String : AnyObject]
or
//MARK:- Dictionary String with Any Object
let dic5 = ["name": fullname, "imageurl": imgurl, "language": imgurl] as [String : AnyObject]
//MARK:- More Easy Way
let dic6a = NSDictionary()
let dic6b = NSMutalbeDictionary()
回答by Lee Probert
I'm playing with this too. It seems strange that you can just declare an empty dictionary and then add a key/value pair to it like so :
我也在玩这个。你可以声明一个空字典,然后像这样添加一个键/值对,这似乎很奇怪:
var emptyDictionary = Dictionary<String, Float>()
var flexDictionary = [:]
emptyDictionary["brian"] = 4.5
flexDictionary["key"] = "value" // ERROR : cannot assign to the result of this expression
But you can create a Dictionary that accepts different value types by using the "Any" type like so :
但是您可以使用“Any”类型创建一个接受不同值类型的字典,如下所示:
var emptyDictionary = Dictionary<String, Any>()
emptyDictionary["brian"] = 4.5
emptyDictionary["mike"] = "hello"