美文网首页
Swift 中交集、并集、补集等

Swift 中交集、并集、补集等

作者: 张科_Zack | 来源:发表于2021-04-13 11:07 被阅读0次

设置两个集合 set1 和 set2。 set1元素为 [1, 2, 3, 4], set2 元素为 [2, 3, 4, 5],预期结果:

  • 交集: [2, 3, 4]
  • 并集: [1, 2, 3, 4, 5]
  • 补集: [1, 5]
  • set1中存在而 set2中不存在的: [1]
  • set2 中存在而 set1 中不存在的: [5]
let set1 = Set([1, 2, 3, 4])
let set2 = Set([2, 3, 4, 5])

交集(Intersection)

let intersection = set1.intersection(set2)
// result [2, 3, 4]

并集(Union)

let union = set1.union(set2)
// result [1, 2, 3, 4, 5]

补集(Complement)

let complement = set1.union(set2)
// result [1, 5]

set1中存在而 set2 中不存在的元素

let onlySet1Elements = set1.subtracting(set2)
// result [1]

set2 中存在而 set1 中不存在的元素

let onlySet2Elements = set2.subtracting(set1)
// result [5]

需要说明的是 subtracting方法,如果想获得仅仅set1存在的元素则 set1为调用方法者 set2 为参数, 如果想获得仅仅set2存在的元素则 set2为调用方法者 set1 为参数。

相关文章

网友评论

      本文标题:Swift 中交集、并集、补集等

      本文链接:https://www.haomeiwen.com/subject/oxvqlltx.html