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

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

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

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

let emptyDict = [:]

如何声明一个空字典?


当前回答

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

其他回答

你必须给字典一个类型

// 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 dictList = String: swift中字典的字符串 var arrSectionTitle =字符串数组在swift

要用[:]也就是空字典字面量创建一个空字典,实际上需要首先提供上下文,就像键和值的类型一样。使用[:]创建空字典的正确方法是:

var dict: [String: Int] = [:]

我通常用

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

它很方便你找路

var dict:Dictionary = [:]