Swift Set count

count 属性返回集合中存在的元素的总数。

示例

var employees: Set = ["Ranjy", "Sabby", "Pally"]

// count total number of elements in languages var result = employees.count
print(result) // Output: 3

count 语法

集合 count 属性的语法是

set.count 

其中,setSet 类的一个对象。


count 返回值

count 属性返回集合中存在的元素的总数。


示例 1:Swift Set count

var names: Set = ["Gregory", "Johnny", "Kate"]

// count total elements on names print(names.count)
var employees = Set<String>()
// count total elements on employees print(employees.count)

输出

3
0

在上面的示例中,由于

  • names 包含三个字符串元素,该属性返回 3
  • 如果 employees 是一个空集合,该属性返回 0

示例 2:将 count 与 if...else 结合使用

var numbers: Set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// true because there are 10 elements on numbers if (numbers.count > 5) {
print( "The set size is large") } else { print("The set size is small") }

输出

The set size is large

在上面的示例中,我们创建了一个名为 numbers 的集合,其中包含 10 个元素。

这里,因为集合中有 10 个元素,所以 numbers.count > 5 的计算结果为 true,因此会执行 if 块内的语句。

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

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

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

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