跳到主要内容

Swift 字典 isEmpty 属性

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

示例

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

// 检查 languages 是否为空
var result = languages.isEmpty

print(result)

// 输出: false

isEmpty 语法

字典 isEmpty 属性的语法如下:

dictionary.isEmpty

这里,dictionaryDictionary 类的对象。

isEmpty 返回值

isEmpty 属性返回:

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

示例 1:Swift 字典 isEmpty

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

// 检查 names 是否为空
print(names.isEmpty)

var employees = [String: Int]()

// 检查 employees 是否为空
print(employees.isEmpty)

输出

false
true

在上面的示例中,因为:

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

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

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

// 因为 names 包含三个键值对,所以为 false
if (employees.isEmpty) {

print( "字典为空")
}

else {

print("元素:", employees)
}

输出

元素: ["Ranjy": 50000, "Sabby": 100000]

在这里,employees 字典不为空,所以跳过了 if 块,执行了 else 块。