问题
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