Swift:声明一个空字典 [英] Swift: declare an empty dictionary

查看:205
本文介绍了Swift:声明一个空字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习 swift ,遵循苹果提供的Swift的iBook - Swift编程语言。该书说要创建一个空字典,应该使用 [:] 与将声明数组 [] 相同: / p>

我宣布一个空数组如下:

  let emptyArr = [ ] //或String []()

但是在声明空字典时,我会收到语法错误: / p>

  let emptyDict = [:] 

如何申报一个空字典?

解决方案

  var emptyDictionary = [String:String]()

­

  var populatedDictionary = [key1:value1,key2:value2] 

注意:如果要随着时间更改字典的内容,请将其声明为 var (变量)。您可以将一个空字典声明为 let (常量),但如果您有意图随时间更改其内容,则无意义,因为常数初始化后不能更改。






旧答案



创建类型为< String,String> 的空字典如下所示:

  var emptyDictionary = Dictionary< String,String>()


I am beginning to learn swift by following the iBook-The Swift Programming Language on Swift provided by Apple. The book says to create an empty dictionary one should use [:] same as while declaring array as []:

I declared an empty array as follows :

let emptyArr = [] // or String[]()

But on declaring empty dictionary, I get syntax error:

let emptyDict = [:]

How do I declare an empty dictionary?

解决方案

var emptyDictionary = [String: String]()

­

var populatedDictionary = ["key1": "value1", "key2": "value2"]

Note: if you are going to change the contents of the dictionary over time then declare it as a var (variable). You can declare an empty dictionary as a let (constant) but it is pointless if you have the intention of changing its contents over time, since constant can't be changed after it has been initialized.


Old answer:

Creating an empty dictionary of type <String, String> would look as follows:

var emptyDictionary = Dictionary<String, String>()

这篇关于Swift:声明一个空字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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