Syntax to create Dictionary in Swift

限于喜欢 提交于 2019-12-23 02:38:36

问题


As far as I know there are two ways to create an empty dictionary in swift

var randomDict = [Int:Int]()

or

var randomDict = Dictionary<Int, Int>()

Is there any difference between these? Both versions seems to work just the same.


回答1:


No, both are same. From Apple's Book on Swift:

The type of a Swift dictionary is written in full as Dictionary<Key, Value> You can also write the type of a dictionary in shorthand form as [Key: Value]. Although the two forms are functionally identical, the shorthand form is preferred.

So

var randomDict = [Int:Int]()

and

var randomDict = Dictionary<Int, Int>()

both calls the initializer which creates an empty dictionary and are basically the same in different form.




回答2:


A third way you could do it is:

var randomDict:[Int:Int] = [:]

They're all equivalent as far as the code goes. I prefer one of the shorthand versions.



来源:https://stackoverflow.com/questions/29354511/syntax-to-create-dictionary-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!