斯威夫特 - 字典


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 允许您从数组(键值对)创建字典。

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

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

var Distance = [2000,10, 620]

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

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

上面的代码行将创建一个以城市为键、以距离为值的字典 -

过滤

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

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

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

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

字典分组

Swift 4 允许您创建字典值分组。

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循环迭代字典中的整个键值对集,如以下示例所示 -

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

计数属性

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

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

空的财产

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

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