Swift 程序检查字典是否为空

swiftserver side programmingprogramming更新于 2025/9/21 13:07:17

本教程将讨论如何编写 Swift 程序检查字典是否为空。

字典用于以键值对的形式存储数据,其排序规则不分先后顺序。字典中键的类型相同,值的类型也相同。每个键都充当字典中关联值的标识符,每个值都有一个唯一的键。Swift 字典就像真正的字典一样。它根据标识符循环查找值。

语法

以下是创建字典的语法 -

var mydict = [KeyType: ValueType]()
或
var mydict : [KeyType: ValueType] = [key1:value1, key2:value2, key3:value3]

要检查给定字典是否为空,我们可以使用以下任一方法 -

  • 使用 count 属性

  • 使用 isEmpty 属性

方法 1 - 使用 count 属性

要检查给定字典是否为空,我们检查字典的大小。如果字典的大小为 0,则字典为空,否则不为空。因此,为了找到字典的大小,我们使用 count 属性。

下面是相同的演示 -

输入

假设我们的给定输入是 -

Mydict = [1: "Mona", 2: "Noh", 3: "Tarzen"]
NO! The dictionary is not empty
Here Mydict dictionary is not empty because the size of the Mydict is 3

语法

语法如下:-

dictName.count

算法

算法如下:-

  • 步骤 1 - 使用键值对创建字典。

  • 步骤 2 - 使用 count 属性计算字典的大小。

var size1 = mydict1.count
var size2 = mydict2.count
  • 步骤 3 - 如果如果大小等于 0,则字典为空。否则,字典不为空。

  • 步骤 4 − 打印输出

示例

以下程序演示如何计算字典的大小。

import Foundation import Glibc // Creating dictionaries var mydict1 : [Int:Int] = [2:34, 4:56, 8:98, 5:3803, 6:23] var mydict2: [Int:String] = [:] // Calculating the size of dictionaries var size1 = mydict1.count var size2 = mydict2.count // Checking if the given dictionaries are empty or not if (size1 == 0){ print("mydict1 is empty") } else{ print("mydict1 is not empty") } if (size2 == 0){ print("mydict2 is empty") } else{ print("mydict2 is not empty") }

输出

mydict1 is not empty
mydict2 is empty

在上面的代码中,我们有两个字典:mydict1 和 mydict2。现在我们使用 count 属性检查它们是否为空。因此,首先我们使用 count 属性计算它们的大小。

var size1 = mydict1.count
var size2 = mydict2.count

现在我们检查它们是否为空 -

if (size1 == 0) // 条件为 false{
    print("mydict1 非空")
}
if (size2 == 0) // 条件为 true{
    print("mydict2 为空")
}

方法 2 - 使用 isEmpty 属性

要检查给定的字典是否为空,我们使用 isEmpty 属性。如果给定的字典为空,则此属性返回 true。否则,它将返回 false。

下面是相同的演示 -

输入

假设我们给定的输入是 -

Mydict = []
YES! The dictionary is not empty

此处,Mydict 字典为空,因此 isEmpty 将返回 true。

语法

语法如下:-

dictName.isEmpty

算法

算法如下:-

  • 步骤 1 - 使用键值对创建字典。

  • 步骤 2 - 使用 isEmpty 属性检查给定字典是否为空。

mydict1.isEmpty
  • 步骤 3 - 打印输出

示例

以下程序展示了如何计算字典的大小。

import Foundation import Glibc // Creating dictionaries var mydict1 : [Int:String] = [1: "CAR", 2: "BUS", 3:"BIKE"] var mydict2: [String:String] = [:] // Checking if the given dictionaries are empty or not if (mydict1.isEmpty == true){ print("mydict1 is empty") } else{ print("mydict1 is not empty") } if (mydict2.isEmpty == true){ print("mydict2 is empty") } else{ print("mydict2 is not empty") }

输出

mydict1 is not empty
mydict2 is empty

在上面的代码中,我们有两个字典:mydict1 和 mydict2。现在我们使用 isEmpty 属性来检查它们是否为空。

if (mydict1.isEmpty == true) // 条件为 false{
    print("mydict1 为空")
}
if (mydict2.isEmpty == true) // 条件为 true{
    print("mydict2 为空")
}
else{
    print("mydict2 非空")
}


相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部