Swift程式:檢查兩個集合是否相等


Swift 提供一個等號運算子 (==) 來檢查給定的兩個集合是否相等。這裡兩個集合的相等意味著這兩個集合在大小和元素方面都必須相同。所以,如果兩個集合相同,則等號運算子返回 true。否則,等號運算子將返回 false。

語法

set1 == set2

其中 set1 和 set2 是兩個集合,使用 == 運算子檢查它們是否相等。如果兩個集合相等,則此運算子將返回 true。否則,它將返回 false。

示例

在下面的示例中,我們建立並初始化四個集合。然後,我們使用 == 運算子檢查它們是否彼此相等。如果它們相等,我們將得到輸出“Yes! set1 is equal to set2”。否則,我們將得到輸出“No! Both the sets are not equal”。

import Foundation
import Glibc

// Creating sets 
let set1: Set<Int> = [2, 5, 1, 8]
let set2: Set<Int> = [8, 2, 1, 5]
let set3: Set<Int> = [4, 7, 2, 8, 8]
let set4: Set<Int> = [2, 5, 1, 8, 3]

if set1 == set2 {
   print("Yes! set1 is equal to set2")
} else {
   print("No! Both the sets are not equal")
}

if set3 == set4 {
   print("Yes! set3 is equal to set4")
} else {
   print("No! Both the sets are not equal")
}

if set1 == set4 {
   print("Yes! set1 is equal to set4")
} else {
   print("No! Both the sets are not equal")
}

輸出

Yes! set1 is equal to set2
No! Both the sets are not equal
No! Both the sets are not equal

結論

這就是我們如何檢查兩個集合是否相等的方法。這裡元素的順序無關緊要,只有大小和元素重要,如果這兩個指定集合的大小和元素都相等,則集合相等,否則不相等。

更新於:2023年4月6日

220 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告