使用 Swift 5,您可以使用以下路径之一来查找两个数组是否具有共同元素。
#1。使用SetisDisjoint(with:)方法
Set 有一个名为isDisjoint(with:) 的方法。 isDisjoint(with:) 有以下声明:
func isDisjoint(with other: Set<Element>) -> Bool
返回一个布尔值,指示该集合是否没有与给定序列相同的成员。
为了测试两个数组是否没有共同元素,可以使用下面实现isDisjoint(with:)的Playground示例代码:
let array1 = [1, 3, 6, 18, 24]
let array2 = [50, 100, 200]
let hasNoCommonElement = Set(array1).isDisjoint(with: array2)
print(hasNoCommonElement) // prints: true
#2。使用Setintersection(_:)方法
Set 有一个名为intersection(_:) 的方法。 intersection(_:) 有以下声明:
func intersection<S>(_ other: S) -> Set<Element> where Element == S.Element, S : Sequence
返回一个新集合,其中包含该集合和给定序列共有的元素。
为了测试两个数组是否没有共同元素或一个或多个共同元素,您可以使用下面实现intersection(_:)的Playground示例代码:
let array1 = [1, 3, 6, 18, 24]
let array2 = [2, 3, 18]
let intersection = Set(array1).intersection(array2)
print(intersection) // prints: [18, 3]
let hasCommonElement = !intersection.isEmpty
print(hasCommonElement) // prints: true