Swift 字典 isEmpty

isEmpty 属性用于检查字典是否为空。

示例

var languages = ["Swift": 2014, "C": 1972, "Java": 1995]

// check if leanguages is empty or not var result = languages.isEmpty
print(result) // Output: false

isEmpty 语法

字典 isEmpty 属性的语法是:

dictionary.isEmpty 

这里,dictionaryDictionary 类的一个对象。


isEmpty返回值

isEmpty 属性返回:

  • true - 如果字典不包含任何元素
  • false - 如果字典包含一些元素

示例 1:Swift 字典 isEmpty

var names = ["Alcaraz": 2003, "Sinner": 2000, "Nadal": 1985]

// check if names is empty or not print(names.isEmpty)
var employees = [String: Int]()
// check if employees is empty or not print(employees.isEmpty)

输出

false
true

在上面的示例中,由于

  • names 包含三个键/值对,该属性返回 false
  • employees 是一个空字典,该属性返回 true

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

var employees = ["Ranjy": 50000, "Sabby": 100000]

// false because names contains three key/value pairs if (employees.isEmpty) {
print( "Dictionary is empty") } else { print("Elements:", employees) }

输出

Elements: ["Ranjy": 50000, "Sabby": 100000]

这里,employees 字典不为空,因此会跳过 if 代码块,并执行 else 代码块。

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

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

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

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