Swift程序:检查集合是否为空


在Swift中,集合用于创建唯一元素的集合。在集合中,元素并非按照特定顺序排列。现在,为了检查集合是否为空,Swift提供了一个名为isEmpty的内置属性。如果给定的集合为空,此属性将返回true。否则,它将返回false。

语法

newSet.isEmpty

其中newSet是集合的名称,我们可以使用点运算符访问isEmpty属性。此属性的返回类型是bool,这意味着如果它返回true,则表示集合为空。如果返回false,则表示集合不为空。

示例1

在这个例子中,我们创建了三种不同类型的集合。现在,使用isEmpty属性,我们检查它们是否为空。如果我们得到true,这意味着集合为空。否则,指定的集合不为空。

import Foundation
import Glibc

// Creating sets
var myFavNum: Set<Int> = [12, 98, 34, 1, 34, 22, 67]
var myColor: Set<String> = []
var mySet = Set<Double>()
var myNum: Set = [45.4, 32.1, 2.3, 5.6, 32.2, 44.3]

// checking if the set is empty or not
print("Is myFavNum set is empty?:", myFavNum.isEmpty)
print("Is myColor set is empty?:", myColor.isEmpty)
print("Is mySet set is empty?:", mySet.isEmpty)
print("Is myNum set is empty?:", myNum.isEmpty)

输出

Is myFavNum set is empty?: false
Is myColor set is empty?: true
Is mySet set is empty?: true
Is myNum set is empty?: false

示例2

在下面的例子中,我们创建了两个集合。现在,我们使用if else语句和条件(myFavNum.isEmpty == true)来检查给定的集合是否为空。如果集合为空,则打印“给定的集合为空”。否则,打印“集合不为空”。

import Foundation
import Glibc

// Creating sets
var myFavNum: Set = [22, 43, 33, 56, 34, 88, 16]
var myColor: Set<String> = []

// Checking if the set is empty or not
if (myFavNum.isEmpty == true){
   print("The given set is empty")
}
else{
   print("The set is not empty")
}

// Checking if the set is empty or not
if (myColor.isEmpty == true){
   print("The given set is empty")
}
else{
   print("The set is not empty")
}

输出

The set is not empty
The given set is empty

结论

这就是我们如何检查集合是否为空的方法。这里的isEmpty属性将结果返回为bool值,因此不需要解包可选值。

更新于:2023年4月6日

381 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.