在 Swift 中初始化字典的不同方法? [英] Different ways to initialize a dictionary in Swift?
问题描述
据我所知,在 Swift 中有 4 种方法可以声明字典:
As far as I know, there are 4 ways to declare a dictionary in Swift:
var dict1: Dictionary<String, Double> = [:]
var dict2 = Dictionary<String, Double>()
var dict3: [String:Double] = [:]
var dict4 = [String:Double]()
这四个选项似乎产生了相同的结果.
It seems these four options yields the same result.
这两者有什么区别?
推荐答案
您所做的只是注意到您可以:
All you're doing is noticing that you can:
使用显式的变量类型,或者让 Swift 根据分配给它的值来推断变量的类型.
Use explicit variable typing, or let Swift infer the type of the variable based on the value assigned to it.
使用正式指定的泛型结构符号Dictionary
,或者使用内置的语法糖"来描述字典类型[String:Double]
.
Use the formal specified generic struct notation Dictionary<String,Double>
, or use the built-in "syntactic sugar" for describing a dictionary type [String:Double]
.
二乘以二等于四.
然后实际上您忽略了一些可能性;例如,你可以说
And then there are in fact some possibilities you've omitted; for example, you could say
var dict5 : [String:Double] = [String:Double]()
当然,在现实生活中,您可能没有做这些事情,而只需将实际字典分配给您的变量:
And of course in real life you are liable to do none of these things, but just assign an actual dictionary to your variable:
var dict6 = ["howdy":1.0]
这篇关于在 Swift 中初始化字典的不同方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!