Swift字典

Swift字典

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

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

字典键可以是整数,也可以是字符串,但它在字典中作为键是唯一的。

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

1.创建字典

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

var someDict = [KeyType: ValueType]()

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

var someDict = [Int: String]()

下面是一个从一组给定值中来创建字典的示例 -

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

2.基于序列的字典初始化

Swift 4允许从数组来创建字典(键值对)。

var cities = ["Haikou","Beijing","Nanjing"]

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

var Distance = [2000,10, 620]

下面是一个从一组给定值中来创建字典的示例 -

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

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

3.过滤

Swift 4允许过滤字典中的值。参考以下示例代码 -

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

如果运行上面的代码,closeCities字典将是 -

["Beijing" : 10 , "Nanjing" : 620]

4.字典分组

Swift 4允许创建字典值的分组。参考以下代码 -

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

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

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

上面代码的结果将是 -

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

5.访问词典

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

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

count属性

可以使用字典的只读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

count属性

可以使用字典的只读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