在 Swift 中创建字典的语法 [英] Syntax to create Dictionary in Swift
问题描述
据我所知有两种方法可以快速创建一个空字典
var randomDict = [Int:Int]()
或
var randomDict = Dictionary()
这两者有什么区别吗?两个版本似乎都一样.
不,两者是一样的.摘自 Apple 的 Swift 书籍:><块引用>
Swift 字典的类型全写为 Dictionary
您还可以将字典的类型以速记形式编写为 [Key: Value]
.尽管这两种形式在功能上是相同的,但首选简写形式.
所以
var randomDict = [Int:Int]()
和
var randomDict = Dictionary()
两者都调用了创建空字典的初始化器,并且在不同的形式上基本相同.
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.
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.
这篇关于在 Swift 中创建字典的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!