目录

swift - 字典( Dictionaries)

Swift 4 dictionaries用于存储相同类型的无序值列表。 Swift 4进行了严格的检查,即使是错误也不允许你在字典中输入错误的类型。

Swift 4字典使用称为key唯一标识符来存储值,以后可以通过相同的密钥引用和查找该值。 与数组中的项目不同, dictionary项目没有指定的顺序。 当您需要根据标识符查找值时,可以使用dictionary

字典键可以是整数,也可以是没有限制的字符串,但它在字典中应该是唯一的。

如果将创建的字典分配给变量,则它始终是可变的,这意味着您可以通过添加,删除或更改其项来更改它。 但是如果将字典分配给常量,那么该字典是不可变的,并且其大小和内容不能更改。

创建字典

您可以使用以下初始化语法创建特定类型的空字典 -

var someDict = [KeyType: ValueType]()

您可以使用以下简单语法创建一个空字典,其键将是Int类型,关联的值将是字符串 -

var someDict = [Int: String]()

这是一个从一组给定值创建字典的示例 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

基于序列的初始化

Swift 4允许您从数组创建Dictionary(键值对)。

var cities = [“Delhi”,”Bangalore”,”Hyderabad”]

您可以使用以下简单语法创建一个空字典,其键将是Int类型,关联的值将是字符串 -

var Distance = [2000,10, 620]

这是一个从一组给定值创建字典的示例 -

let cityDistanceDict = Dictionary(uniqueKeysWithValues: zip(cities, Distance))

上面的代码行将创建一个字典,其中Cities为键,Distance为Value -

Filtering

Swift 4允许您过滤字典中的值。

var closeCities = cityDistanceDict.filter { $0.value < 1000 }

如果我们运行上面的代码,我们的closeCities字典将是。

["Bangalore" : 10 , "Hyderabad" : 620]

字典分组

Swift 4允许您创建Dictionary值的分组。

var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"]

您可以使用以下简单语法根据第一个字母对字典值进行分组。

var GroupedCities = Dictionary(grouping: cities ) { $0.first! }

上面代码的结果将是

["D" :["Delhi","Dehradun"], "B" : ["Bengaluru","Bihar"], "H" : ["Hyderabad"]]

访问词典

您可以使用下标语法从字典中检索值,并在字典名称后面的方括号内传递要检索的值的键,如下所示 -

var someVar = someDict[key]

让我们检查以下示例来创建,初始化和访问字典中的值 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someVar = someDict[1]
print( "Value of key = 1 is \(someVar)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )

编译并执行上述代码时,会产生以下结果 -

Value of key = 1 is Optional("One")
Value of key = 2 is Optional("Two")
Value of key = 3 is Optional("Three")

修改词典

您可以使用updateValue(forKey:)方法将现有值添加到字典的给定键。 此方法返回字典值类型的可选值。 这是一个简单的例子 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict.updateValue("New value of one", forKey: 1)
var someVar = someDict[1]
print( "Old value of key = 1 is \(oldVal)" )
print( "Value of key = 1 is \(someVar)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )

编译并执行上述代码时,会产生以下结果 -

Old value of key = 1 is Optional("One")
Value of key = 1 is Optional("New value of one")
Value of key = 2 is Optional("Two")
Value of key = 3 is Optional("Three")

您可以通过在给定键上分配新值来修改字典的现有元素,如以下示例所示 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict[1]
someDict[1] = "New value of one"
var someVar = someDict[1]
print( "Old value of key = 1 is \(oldVal)" )
print( "Value of key = 1 is \(someVar)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )

编译并执行上述代码时,会产生以下结果 -

Old value of key = 1 is Optional("One")
Value of key = 1 is Optional("New value of one")
Value of key = 2 is Optional("Two")
Value of key = 3 is Optional("Three")

删除键值对

您可以使用removeValueForKey()方法从字典中删除键值对。 此方法删除键值对(如果存在)并返回已删除的值,如果不存在值则返回nil。 这是一个简单的例子 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var removedValue = someDict.removeValue(forKey: 2)
print( "Value of key = 1 is \(someDict[1])" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )

编译并执行上述代码时,会产生以下结果 -

Value of key = 1 is Optional("One")
Value of key = 2 is nil
Value of key = 3 is Optional("Three")

您还可以使用下标语法通过为该键指定值nil来从字典中删除键值对。 这是一个简单的例子 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
someDict[2] = nil
print( "Value of key = 1 is \(someDict[1])" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )

编译并执行上述代码时,会产生以下结果 -

Value of key = 1 is Optional("One")
Value of key = 2 is nil
Value of key = 3 is Optional("Three")

迭代字典

您可以使用for-in循环迭代Dictionary中的整组键值对,如以下示例所示 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (index, keyValue) in someDict.enumerated() {
   print("Dictionary key \(index) - Dictionary value \(keyValue)")
}

编译并执行上述代码时,会产生以下结果 -

Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One

您可以使用enumerate()函数返回项目的索引及其(键,值)对,如下例所示 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
   print("Dictionary key \(key) - Dictionary value \(value)")
}

编译并执行上述代码时,会产生以下结果 -

Dictionary key 0 - Dictionary value (key: 2, value: "Two")
Dictionary key 1 - Dictionary value (key: 3, value: "Three")
Dictionary key 2 - Dictionary value (key: 1, value: "One")

转换为数组

您可以从给定字典中提取键值对列表,以便为键和值构建单独的数组。 这是一个例子 -

var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)
print("Print Dictionary Keys")
for (key) in dictKeys {
   print("\(key)")
}
print("Print Dictionary Values")
for (value) in dictValues {
   print("\(value)")
}

编译并执行上述代码时,会产生以下结果 -

Print Dictionary Keys
2
3
1
Print Dictionary Values
Two
Three
One

计数属性

您可以使用字典的只读count属性来查找字典中的项目数,如下所示 -

var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
print("Total items in someDict1 = \(someDict1.count)")
print("Total items in someDict2 = \(someDict2.count)")

编译并执行上述代码时,会产生以下结果 -

Total items in someDict1 = 3
Total items in someDict2 = 2

空财产

您可以使用字典的只读empty属性来查明字典是否为空,如下所示 -

var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
var someDict3:[Int:String] = [Int:String]()
print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")

编译并执行上述代码时,会产生以下结果 -

someDict1 = false
someDict2 = false
someDict3 = true
↑回到顶部↑
WIKI教程 @2018