斯威夫特 - 字典
Swift 是一种编程语言,旨在与 Apple 的 Cocoa 和 Cocoa Touch 框架配合使用。它旨在成为 Objective-C 的现代、安全和灵活的替代方案。它在构建时考虑到了开源社区,并由 Swift 社区的成员积极开发。 Swift 是 Objective-C 的现代、安全和灵活的替代方案。
Swift 有一个叫做字典的东西,它是键值对的集合。这些键值对的集合称为字典。它是键值对的无序集合。在字典中,唯一标识符称为键,键存储值。当字典分配给变量时,这意味着字典是可变的(您可以修改),但是当字典分配给常量时,它是不可变的(您不能修改)。在字典中,键可以是字符串、整数等任何类型。在本文中,我们将了解 Swift 中的字典集合类型。
创建字典
在 swift 中,字典是键值对的集合。我们可以使用任何类型的数据作为键,使用任何类型的数据作为值。我们可以使用 (key:value) 语法创建字典。密钥应始终是单个项目。但值可以是单个项目或项目集合,如数组或字典。要创建字典,我们使用以下语法:
句法:
var someDictionary = [keyType: valueType](key : value)
这里,keyType 和 valueType 是字典中键和值的类型,它们之间用冒号分隔。
例子:
Swift
// Swift program to create a dictionary
var someDictionary: [String: String] = ["fruit": "Apple", "vegetable": "Carrot"]
// Displaying key-value pair
print(someDictionary)
Swift
// Swift program to change the value of dictionary
// Creating a dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit",
"three": "Tony"]
// Displaying dictionary
print("Original dictionary: ", someDictionary)
// Changing the value of dictionary
someDictionary["two"] = "Priya"
// Displaying dictionary
print("Updated dictionary: ", someDictionary)
Swift
// Swift program to accessing keys of dictionary
// Creating a dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit",
"three": "Tony"]
// Accessing all the keys from the dictionary
// Using keys property
var result = Array(someDictionary.keys)
// Displaying keys
print("Keys:", result)
Swift
// Swift program to accessing values of dictionary
// Creating a dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit",
"three": "Tony"]
// Accessing all the values from the dictionary
// Using values property
var result = Array(someDictionary.values)
// Displaying values
print("Values:", result)
Swift
// Swift program to iterating over a dictionary
// Creating a dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit",
"three": "Tony"]
// Iterate over dictionary
// Using for-in loop
for (key, value) in someDictionary
{
// Print key and value
print("\(key): \(value)")
}
Swift
// Swift program to create a dictionary from an array
// Creating arrays
var someArray = ["one", "two", "three"]
var someArray2 = ["Mohit", "Rohit", "Tony"]
// Creating a dictionary from an array
var someDictionary = Dictionary(uniqueKeysWithValues: zip(
someArray, someArray2))
// Displaying the dictionary
print(someDictionary)
Swift
// Swift program to remove key-value pair from the dictionary
// Creating a dictionary
var someDictionary = ["key1": "value1", "key2": "value2"]
// Removing the element from the dictionary
// Using removeValue() method
someDictionary.removeValue(forKey: "key1")
// Displaying the dictionary
print(someDictionary)
Swift
// Swift program to convert a dictionary to an array
// Creating and initializing dictionary
var dict = ["Arpit":100, "Robin":90, "Nami":90]
// Converting dictionary to array
// Here, dictArray1 array stores keys
var dictArray1 = Array(dict.keys)
// Here, dictArray1 array stores values
var dictArray2 = Array(dict.values)
// Displaying the array of keys
print(dictArray1)
// Displaying the array of values
print(dictArray2)
Swift
// Swift program to count the elements of dictionary
// Creating and initializing dictionary
var planets = ["Mercury": "The closest planet to the sun",
"Venus": "The second closest planet to the sun",
"Earth": "The third closest planet to the sun",
"Mars": "The fourth closest planet to the sun",
"Jupiter": "The fifth closest planet to the sun",
"Saturn": "The sixth closest planet to the sun",
"Uranus": "The seventh closest planet to the sun",
"Neptune": "The eighth closest planet to the sun"]
// Count the the planets
// Using count property
print(" Total number of planets in our solar system are \(planets.count)")
Swift
// Swift program to check if the dictionary is empty or not
// Creating and initializing dictionary
var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
// Creating empty dictionary
var emptyDictionary = [String: String]()
// Creating and initializing dictionary
var fruits = [ "Apple": "Red", "Orange": "Orange",
"Banana": "Yellow" ]
// Checking if the number dictionary is empty or not
// Using isEmpty property
print("is numbers dictionary empty? \(numbers.isEmpty)")
// Checking if the emptyDictionary dictionary
// is empty or not. Using isEmpty property
print("is emptyDictionary dictionary empty? \(emptyDictionary.isEmpty)")
// Checking if the fruits dictionary
// is empty or not. Using isEmpty property
print("is fruits dictionary empty? \(fruits.isEmpty)")
输出:
["vegetable": "Carrot", "fruit": "Apple"]
创建一个空字典
空字典是其中没有键值对的字典。空字典没有任何初始值。它可用于以键值对的形式存储数据。它充当存储数据的容器。要创建空字典,请使用以下语法:
句法:
var emptyDictionary = [keyType: valueType][:]
这里,keyType 和 valueType 是字典中键和值的类型。而 ([:]) 是一个空字典字面量,用于创建一个空字典。
更改字典的值
在 Swift 中,我们可以使用 [] 更改字典的值。方括号 [] 更改与字典中给定键关联的值。同样,您也可以在字典中添加新的键值对。如果给定的键不存在,则将该键和值对添加到字典中。
句法:
Dictionary_name[key] = value
例子:
迅速
// Swift program to change the value of dictionary
// Creating a dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit",
"three": "Tony"]
// Displaying dictionary
print("Original dictionary: ", someDictionary)
// Changing the value of dictionary
someDictionary["two"] = "Priya"
// Displaying dictionary
print("Updated dictionary: ", someDictionary)
输出:
Original dictionary: ["two": "Rohit", "one": "Mohit", "three": "Tony"]
Updated dictionary: ["two": "Priya", "one": "Mohit", "three": "Tony"]
访问 Dictionary 的元素
在字典中,我们可以很容易地分别访问键和值。
1. 访问密钥
要访问字典的键,我们使用keys属性。此属性返回字典中的所有键。
句法:
Dictionary_name.keys
例子:
迅速
// Swift program to accessing keys of dictionary
// Creating a dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit",
"three": "Tony"]
// Accessing all the keys from the dictionary
// Using keys property
var result = Array(someDictionary.keys)
// Displaying keys
print("Keys:", result)
输出:
Keys: ["two", "three", "one"]
2. 访问值
要访问字典的值,我们使用values属性。此属性返回字典中的所有值。
句法:
Dictionary_name.values
例子:
迅速
// Swift program to accessing values of dictionary
// Creating a dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit",
"three": "Tony"]
// Accessing all the values from the dictionary
// Using values property
var result = Array(someDictionary.values)
// Displaying values
print("Values:", result)
输出:
Values: ["Tony", "Mohit", "Rohit"]
遍历字典
有时我们需要遍历一个字典,而手动使用下标来访问字典中每个键值对的某个键的值是不可行的。所以我们可以使用 for-in 循环来遍历字典。请记住,字典中键值对的顺序不能保证与插入它们的顺序相同。
句法:
for (key, value) in someDictionary {}
例子:
迅速
// Swift program to iterating over a dictionary
// Creating a dictionary
var someDictionary = ["one": "Mohit", "two": "Rohit",
"three": "Tony"]
// Iterate over dictionary
// Using for-in loop
for (key, value) in someDictionary
{
// Print key and value
print("\(key): \(value)")
}
输出:
three: Tony
one: Mohit
two: Rohit
从数组创建字典
如果我们有两个大小相同的数组,并且我们想要合并它们,以形成一个字典,其中键作为第一个数组,值作为第二个数组,那么您可以在 Swift 中执行此操作。两个数组的大小应该相同。
句法:
var someDictionary = Dictionary(uniqueKeysWithValues: zip(someArray, someArray2))
这里,array1 是键,array2 是值。所以,上面的语法将创建一个字典,键为array1,值为array2
例子:
迅速
// Swift program to create a dictionary from an array
// Creating arrays
var someArray = ["one", "two", "three"]
var someArray2 = ["Mohit", "Rohit", "Tony"]
// Creating a dictionary from an array
var someDictionary = Dictionary(uniqueKeysWithValues: zip(
someArray, someArray2))
// Displaying the dictionary
print(someDictionary)
输出:
["one": "Mohit", "two": "Rohit", "three": "Tony"]
从字典中删除项目
正如我们所看到的,一种获取和设置字典中键值的方法。但有时我们想从字典中删除一个键值对。因此,要从字典中删除键值对,我们使用removeValue(forKey:) 方法。此方法返回已删除键的值,如果该键不存在于字典中,则返回 nil。
句法:
dictionary.removeValue(forKey: key)
例子:
迅速
// Swift program to remove key-value pair from the dictionary
// Creating a dictionary
var someDictionary = ["key1": "value1", "key2": "value2"]
// Removing the element from the dictionary
// Using removeValue() method
someDictionary.removeValue(forKey: "key1")
// Displaying the dictionary
print(someDictionary)
输出:
["key2": "value2"]
将字典转换为数组
Swift 允许我们将字典转换为键值对数组。在这里,将创建两个数组,一个用于存储键,一个用于存储值。
句法:
Array(dictionary)
其中dictionary是我们要转换为数组的字典。
例子:
迅速
// Swift program to convert a dictionary to an array
// Creating and initializing dictionary
var dict = ["Arpit":100, "Robin":90, "Nami":90]
// Converting dictionary to array
// Here, dictArray1 array stores keys
var dictArray1 = Array(dict.keys)
// Here, dictArray1 array stores values
var dictArray2 = Array(dict.values)
// Displaying the array of keys
print(dictArray1)
// Displaying the array of values
print(dictArray2)
输出:
["Arpit", "Robin", "Nami"]
[100, 90, 90]
字典属性
Swift 提供了许多属性和方法来帮助您使用字典。 count 和 empty 属性是字典最重要的属性。 count 属性返回字典中键值对的数量。如果字典没有键值对,则空属性返回 true,如果字典至少有一个键值对,则返回 false。
计数属性
Count 属性返回给定字典中存在的键值对的计数。当您要遍历字典时,此属性很有用。它返回一个整数值,即字典中键值对的数量。
句法:
dictionary.count()
这里, dictionary是字典的名称, count是属性的名称。
例子:
迅速
// Swift program to count the elements of dictionary
// Creating and initializing dictionary
var planets = ["Mercury": "The closest planet to the sun",
"Venus": "The second closest planet to the sun",
"Earth": "The third closest planet to the sun",
"Mars": "The fourth closest planet to the sun",
"Jupiter": "The fifth closest planet to the sun",
"Saturn": "The sixth closest planet to the sun",
"Uranus": "The seventh closest planet to the sun",
"Neptune": "The eighth closest planet to the sun"]
// Count the the planets
// Using count property
print(" Total number of planets in our solar system are \(planets.count)")
输出:
Total number of planets in our solar system are 8
isEmpty 属性
假设我们有一本字典,我们想对它执行一些操作。如果字典为空,我们就不能对其进行任何操作。因此,我们可以使用 empty 属性来检查字典是否为空。如果字典没有键值对,则空属性返回 true,如果字典至少有一个键值对,则返回 false。
句法:
dictionary.isEmpty()
在这里,字典是字典的名称, isEmpty是属性的名称。
例子:
迅速
// Swift program to check if the dictionary is empty or not
// Creating and initializing dictionary
var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
// Creating empty dictionary
var emptyDictionary = [String: String]()
// Creating and initializing dictionary
var fruits = [ "Apple": "Red", "Orange": "Orange",
"Banana": "Yellow" ]
// Checking if the number dictionary is empty or not
// Using isEmpty property
print("is numbers dictionary empty? \(numbers.isEmpty)")
// Checking if the emptyDictionary dictionary
// is empty or not. Using isEmpty property
print("is emptyDictionary dictionary empty? \(emptyDictionary.isEmpty)")
// Checking if the fruits dictionary
// is empty or not. Using isEmpty property
print("is fruits dictionary empty? \(fruits.isEmpty)")
输出:
is numbers dictionary empty? false
is emptyDictionary dictionary empty? true
is fruits dictionary empty? false