在 Swift 中创建字典的语法 [英] Syntax to create Dictionary in Swift

查看:29
本文介绍了在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆