📜  Swift-字典

📅  最后修改于: 2020-12-25 04:29:48             🧑  作者: Mango


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

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

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

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

创建字典

您可以使用以下初始化程序语法创建某种类型的空字典-

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-

筛选

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