Swift 字典 contains()

contains() 方法检查指定的键或值是否存在于字典中。

示例

var information = ["Sam": 1995, "Keane": 1980, "Hen": 2003]

// check if "Hen" is present as key or not var result = information.contains { $0.key == "Hen" }
print(result) // Output: true

contains() 语法

字典 contains() 方法的语法是:

dictionary.contains{check}

这里,dictionaryDictionary 类的一个对象。


contains() 参数

contains() 方法接受一个参数:

  • check - 一个闭包,用于检查键或值是否存在于 dictionary 中。

contains() 返回值

contains() 方法返回:

  • true - 如果字典包含指定的键或值
  • false - 如果字典不包含指定的键或值

示例 1:Swift 字典 contains()

var information = ["Charlie": 54, "Harvey": 38, "Donna": 34]

//  check if "Harvey" is present as key or not
var result1 = information.contains { $0.key == "Harvey" }
print(result1) // check if 34 is present as value or not
var result2 = information.contains { $0.value == 34 }
print(result2) // check if "harvey" is present as key or not
var result3 = information.contains { $0.key == "harvey" }
print(result3)

输出

true
true
false

在上面的程序中,请注意闭包的定义:

{ $0.key == "Harvey" }

这是一个简写闭包,用于检查字典中是否存在 "Harvey" 键。

$0 是指向传递到闭包的第一个参数的快捷方式。

另外两个闭包定义也都是简写闭包,用于检查键或值是否存在。

这里,

  • "Harvey" 作为键存在于 information 中,因此该方法返回 true
  • "34" 作为 "Donna" 键的值存在,因此该方法返回 true
  • "harvey" 不存在于 information 中,因此该方法返回 false

示例 2:使用 contains() 和 if...else

var information = ["Sam": 1995, "Keane": 1980, "Hen": 2003]

var result = information.contains { $0.key == "Hen" }

if result {
    print("Key is present")
}
else {
    print("Key is not present")
}

输出

Key is present
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战