Swift Set isSubset()

isSubset() 方法当一个集合中的所有元素都存在于另一个集合(作为参数传入)中时,返回 true。如果不存在,则返回 false。

示例

var A: Set = [1, 2, 3]
var B: Set = [1, 2, 3, 4, 5]

// check if A is subset of B or not print(A.isSubset(of: B))
// Output: true

isSubset() 语法

集合 isSubset() 方法的语法是:

set.isSubset(otherSet)

其中,setSet 类的一个对象。


isSubset() 参数

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

  • otherSet - 元素的集合。

isSubset() 返回值

  • 如果 setotherSet 的子集,isSubset() 方法返回 true。如果不是,则返回 false

示例:Swift Set isSubset()

var employees: Set = ["Sabby", "Cathy", "Kenny", "Sammy", "Lanny"]
var developers: Set = ["Sabby", "Lanny"]
var designers: Set = ["Cathy", "Patty"]

// check if developer is subset of employees print(developers.isSubset(of: employees))
// check if developer is subset of employees print(designers.isSubset(of: employees))

输出

true
false

在这里,我们使用 isSubset() 方法来检查一个集合是否是另一个集合的子集。

由于

  • 如果 developersemployees 的子集,该方法返回 true
  • 如果 designers 不是 employees 的子集,该方法返回 false
你觉得这篇文章有帮助吗?

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

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

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