本教程解释了如何在Swift中检查字典中存在的键和值。
Dictionary是Swift中的一种数据存储,用于存储键和值。
让我们声明一个字典,其键为Int,其值为String:
let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]
如何在Swift中找到键是否存在于字典中?
在Swift中,Dictionary[key]如果存在则返回可选值,否则返回nil。
emp[11] != nil 如果key存在于字典中,则返回true,否则返回false,字典中不存在。
import Foundation;
let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]
// check key 11 exists in Dictionary
let keyExists = emp[11] != nil
print(keyExists)
if(keyExists ){
print("Key 11 not exists in Dictionary")
}
// check key 1 exists in Dictionary
let keyExists1 = emp[1] != nil
print(keyExists1)
if(keyExists1 ){
print("Key 1 exists in Dictionary")
}
输出:
false
true
Key 1 exists in Dictionary
检查字典中是否包含值,是否存在于 Swift
dictionary.values 返回值的列表,调用包含值的方法来检查值是否存在。
如果有值存在,它返回真,否则返回假。
下面是一个检查字典中是否包含一个值的例子,在 swift 中。
import Foundation;
let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"]
print(emp.values.contains("john")) // true
print(emp.values.contains("john1")) // false
输出:
true
false