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
这里,dictionary 是 Dictionary
类的一个对象。
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
代码块。