我开始学习swift是通过苹果公司提供的swift上的iBook-The swift Programming Language。这本书说要创建一个空字典,应该使用[:],就像声明数组为[]一样:

我声明一个空数组,如下所示:

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

但是在声明空字典时,我得到语法错误:

let emptyDict = [:]

如何声明一个空字典?


当前回答

你可以用以下方法将其声明为nil:

var assoc : [String:String]

好的是你已经有了排版(注意我用了var和not let,把它们看成可变和不可变)然后你可以稍后再填写:

assoc = ["key1" : "things", "key2" : "stuff"]

其他回答

它很方便你找路

var dict:Dictionary = [:]

你必须给字典一个类型

// empty dict with Ints as keys and Strings as values
var namesOfIntegers = Dictionary<Int, String>()

如果编译器可以推断类型,则可以使用较短的语法

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String

我通常用

var dictionary:[String:String] = [:]
dictionary.removeAll()

var dictList = String: swift中字典的字符串 var arrSectionTitle =字符串数组在swift

你可以像这样简单地声明它:

var emptyDict:NSMutableDictionary = [:]