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

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

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

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

let emptyDict = [:]

如何声明一个空字典?


当前回答

var parking = [Dictionary < String, Double >()]

^这将为[string:double]输入添加一个字典

其他回答

您可以使用以下代码:

var d1 = Dictionary<Int, Int>()
var d2 = [Int: Int]()
var d3: Dictionary<Int, Int> = [Int : Int]()
var d4: [Int : Int] = [:]
var emptyDictionary = [String: String]()

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

注意:如果你打算改变字典的内容,那么就把它声明为一个变量(var)。你可以将一个空字典声明为常量(let),但如果你想要改变它,这将是毫无意义的,因为常量值在初始化后不能被改变。

当你在Swift中声明任何东西时,你需要显式地告诉数据类型或类型可以推断。

斯威夫特3

下面的示例声明了一个字典,其中key为Int类型,value为String类型。

方法1:初始化器

let dic = Dictionary<Int, String>()

方法二:简写语法

let dic = [Int:String]()

方法3:字典直译

var dic = [1: "Sample"]
// dic has NOT to be a constant
dic.removeAll()

你必须给字典一个类型

// 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]输入添加一个字典