Swift 程序在字典中搜索元素
swiftserver side programmingprogramming更新于 2025/9/21 3:22:17
在 Swift 字典中,我们可以借助 contains() 函数搜索作为键或值的元素。contains() 函数将返回一个布尔值,表示是否找到指定的元素(键或值)。
语法
dict.contains{$0.key == "KeyName"}
此处,dict 是字典。contains() 函数返回一个布尔值,表示结果。这里我们在函数中传递一个闭包,它将检查当前键是否等于指定键,然后返回相应的结果。
算法
步骤 1 - 创建一个包含键值对的字典。
步骤 2 - 创建一个变量来存储结果。
步骤 3 - 然后使用 contains() 函数检查指定的键是否存在于给定的字典中。
步骤 4 - 显示输出。
示例
在下面的 Swift 程序中,我们将在字典中搜索元素。因此,我们创建一个包含键值对的字典,然后使用 contains() 方法来检查给定的键是否存在于字典中,为此,我们在函数中传递一个闭包,将所有键与指定的键进行比较并返回布尔结果。
import Foundation
import Glibc
var myCityRank:[String:Int] = ["Delhi": 31, "Goa": 3, "Pune": 1, "Jaipur": 2, "Kolkata": 87]
var result = myCityRank.contains{$0.key == "Goa"}
if (result == true) {
print("Congratulations! Key is found")
} else {
print("Key does not found. Please try again!")
}
输出
Congratulations! Key is found
结论
以上就是我们在字典中搜索元素的方法。使用 contains 方法,我们可以搜索键或值。我们也可以使用 [] 括号来实现同样的效果。但最有效的方法是 contains() 方法。