我开始学习swift是通过苹果公司提供的swift上的iBook-The swift Programming Language。这本书说要创建一个空字典,应该使用[:],就像声明数组为[]一样:
我声明一个空数组,如下所示:
let emptyArr = [] // or String[]()
但是在声明空字典时,我得到语法错误:
let emptyDict = [:]
如何声明一个空字典?
我开始学习swift是通过苹果公司提供的swift上的iBook-The swift Programming Language。这本书说要创建一个空字典,应该使用[:],就像声明数组为[]一样:
我声明一个空数组,如下所示:
let emptyArr = [] // or String[]()
但是在声明空字典时,我得到语法错误:
let emptyDict = [:]
如何声明一个空字典?
当前回答
你必须给字典一个类型
// 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 emptyDictionary = [String: String]()
var populatedDictionary = ["key1": "value1", "key2": "value2"]
注意:如果你打算改变字典的内容,那么就把它声明为一个变量(var)。你可以将一个空字典声明为常量(let),但如果你想要改变它,这将是毫无意义的,因为常量值在初始化后不能被改变。
你必须给字典一个类型
// 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 parking = [Dictionary < String, Double >()]
^这将为[string:double]输入添加一个字典
要用[:]也就是空字典字面量创建一个空字典,实际上需要首先提供上下文,就像键和值的类型一样。使用[:]创建空字典的正确方法是:
var dict: [String: Int] = [:]
我通常用
var dictionary:[String:String] = [:]
dictionary.removeAll()