在 Swift 中创建字典的语法
Syntax to create Dictionary in Swift
据我所知有两种方法可以在 swift
中创建空字典
var randomDict = [Int:Int]()
或
var randomDict = Dictionary<Int, Int>()
这些有什么区别吗?两个版本似乎都一样。
不,两者相同。
来自 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.
所以
var randomDict = [Int:Int]()
和
var randomDict = Dictionary<Int, Int>()
两者都调用创建一个空字典的初始化器,并且在不同的形式下基本相同。
第三种方法是:
var randomDict:[Int:Int] = [:]
就代码而言,它们都是等价的。我更喜欢 shorthand 版本之一。
据我所知有两种方法可以在 swift
中创建空字典var randomDict = [Int:Int]()
或
var randomDict = Dictionary<Int, Int>()
这些有什么区别吗?两个版本似乎都一样。
不,两者相同。 来自 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.
所以
var randomDict = [Int:Int]()
和
var randomDict = Dictionary<Int, Int>()
两者都调用创建一个空字典的初始化器,并且在不同的形式下基本相同。
第三种方法是:
var randomDict:[Int:Int] = [:]
就代码而言,它们都是等价的。我更喜欢 shorthand 版本之一。