字典初始化方式之间的差异 [英] Differences between ways of initializing a dictionary
问题描述
我正在学习Swift,并且想知道初始化空字典的这些方式之间有什么区别?
I'm learning Swift and was wondering what the differences were between these ways of initializing an empty dictionary?
var emptyDic = Dictionary<String, String>()
var emptyDic:[String:String] = [:]
var emptyDic = [String:String]()
这将:
var emptyDic:[String:String]
创建未初始化的字典吗?
create an un-initialized dictionary?
谢谢!
推荐答案
示例1和3在语法上几乎是等效的,因为第3个是第一个的简写.但是在声明1、2和3后,它们在语义上是相同的.因此,与其说是巨大的差异,不如说是个人喜好(对我来说是第三个:).
Example 1 and 3 are almost syntactically equivalent since the 3rd one is a shorthand notation of the first. But after the declaration of 1, 2 and 3 they are semantically the same. So it is more a personal preference (for me the 3rd one :) rather than a huge difference.
但是第四个示例(如您所说)尚未初始化,如果您过早访问它,编译器会警告您.
However the 4th example is (as you said) uninitialized and the compiler will warn you if you want to access it too early.
这篇关于字典初始化方式之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!