Yes, Swift has the Set class.

let array1 = ["a", "b", "c"]
let array2 = ["a", "b", "d"]

let set1:Set<String> = Set(array1)
let set2:Set<String> = Set(array2)

Swift 3.0+ can do operations on sets as:

firstSet.union(secondSet)// Union of two sets
firstSet.intersection(secondSet)// Intersection of two sets
firstSet.symmetricDifference(secondSet)// exclusiveOr

Swift 2.0 can calculate on array arguments:

set1.union(array2)       // {"a", "b", "c", "d"} 
set1.intersect(array2)   // {"a", "b"}
set1.subtract(array2)    // {"c"}
set1.exclusiveOr(array2) // {"c", "d"}

Swift 1.2+ can calculate on sets:

set1.union(set2)        // {"a", "b", "c", "d"}
set1.intersect(set2)    // {"a", "b"}
set1.subtract(set2)     // {"c"}
set1.exclusiveOr(set2)  // {"c", "d"}

If you're using custom structs, you need to implement Hashable.

Thanks to Michael Stern in the comments for the Swift 2.0 update.

Thanks to Amjad Husseini in the comments for the Hashable info.

Answer from joelparkerhenderson on Stack Overflow
🌐
Programiz
programiz.com › swift-programming › library › set › intersection
Swift Set intersection() (With Examples)
The Swift Set intersection() method returns a new set with elements that are common to both sets. The intersection() method returns a new set with elements that are common to both elements. Example var A: Set = [2, 3, 5] var B: Set = [1, 3, 5] // compute intersection between A and B print("A ...
🌐
Codecademy
codecademy.com › docs › swift › sets › .intersection()
Swift | Sets | .intersection() | Codecademy
October 23, 2022 - The .intersection() method returns a new set containing all elements of the set that also belong to the given sequence. ... Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
🌐
Swift Forums
forums.swift.org › using swift
How to do array.intersects(otherArray)? - Using Swift - Swift Forums
March 23, 2018 - Hi all, Is there an easy way to find out if one array has elements in common with another array? Something like this: let modifiers = ["26", "25", "GY", "GN"] let special = ["GA", "GY"] modifiers.intersects(special) // Returns true because "GY" exists in both arrays Is there anything in the ...
🌐
Educative
educative.io › answers › how-to-find-the-intersection-between-a-set-and-an-array-in-swift
How to find the intersection between a set and an array in Swift
Line 2 and 3: We create two sets. Line 6: We create an array. Line 9 and 10: We use the intersection() method to get the intersection between the sets and the array.
🌐
Programiz
programiz.com › swift-programming › library › set › formIntersection
Swift Set formIntersection() (With Examples)
The Swift Set formIntersection() method removes the elements of the set that aren’t also in the given sequence. The formIntersection() method removes the elements of the set that aren't also in the given sequence. Example // create a set A var A: Set = [2, 3, 5] // create an array B var B ...
🌐
Programiz
programiz.com › swift-programming › sets
Swift Sets (With Examples)
We use the intersection() method to perform the intersection between two sets.
🌐
TutorialKart
tutorialkart.com › swift-tutorial › swift-intersection-of-sets
Intersection of Sets in Swift
October 17, 2021 - Set.intersection() returns a new Set with the elements common to both the Sets.
Find elsewhere
🌐
Swift Forums
forums.swift.org › using swift
Question about Set intersection function - Using Swift - Swift Forums
August 24, 2021 - Swift: 5.5.1 Why always return intersection items of set1? Is there any way to return intersection items of set2? thx Result: ===== set1 ===== [Item: 0x00006000026a44c0] name: 1, price: 1, type: set1 [Item: 0x0000600…
🌐
GeeksforGeeks
geeksforgeeks.org › swift › swift-set-operations
Swift - Set Operations - GeeksforGeeks
March 5, 2024 - So the intersection contains the ... intersection of both sets has only common elements. Swift provides an inbuilt intersection() method to find the intersection of two sets....
🌐
GitHub
gist.github.com › 29240ddbef03c942fdc5bf54218a8f2c
Intersection in swift · GitHub
Intersection in swift. GitHub Gist: instantly share code, notes, and snippets.
Top answer
1 of 7
123

You can also use filter and contains in conjunction:

let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]

// only Swift 1
let output = fruitsArray.filter{ contains(vegArray, $0) }

// in Swift 2 and above
let output = fruitsArray.filter{ vegArray.contains($0) }
// or
let output = fruitsArray.filter(vegArray.contains)

Set vs Array for a single computation of common elements

We consider the following code snippet:

let array1: Array = ...
let array2: Array = ...

// `Array`
let commonElements = array1.filter(array2.contains)

// vs `Set`
let commonElements = Array(Set(array1).intersection(Set(array2)))
// or (performance wise equivalent)
let commonElements: Array = Set(array1).filter(Set(array2).contains)

I have made some (artificial) benchmarks with Int and short/long Strings (10 to 100 Characters) (all randomly generated). I always use array1.count == array2.count

I get the following results:

If you have more than critical #(number of) elements converting to a Set is preferable

data         |  critical #elements
-------------|--------------------
         Int |        ~50
short String |       ~100
 long String |       ~200

Explanation of the results

Using the Array approach uses "Brute force"-search which has time complexity O(N^2) where N = array1.count = array2.count which is in contrast to the Set approach O(N). However the conversion from Array to Set and back is very expensive for large data which explains the increase of critical #elements for bigger data types.


Conclusion

For small Arrays with about 100 elements the Array approach is fine but for larger ones you should use the Set approach.

If you want to use this "common elements"-operation multiple times it is advisable to use Sets only if possible (the type of the elements has to be Hashable).

Final Remarks

A conversion from Array to Set is kind of expensive while the conversion from Set to Array is in contrast very inexpensive.

Using filter with .filter(array1.contains) is performance wise faster than .filter{ array1.contains($0) } since:

  • the last one creates a new closure (only once) whereas the first one passes only a function pointer
  • for the last one the call of the closure creates an additional stack frame which costs space and time (multiple times: O(N))
2 of 7
35

Convert them to Set and use intersect() function:

let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]
let fruitsSet = Set(fruitsArray)
let vegSet = Set(vegArray)
let output = Array(fruitsSet.intersection(vegSet))
🌐
GitHub
github.com › OpenMined › SwiftPSI
GitHub - OpenMined/SwiftPSI: A Swift library for private set intersection
A Swift library for private set intersection. Contribute to OpenMined/SwiftPSI development by creating an account on GitHub.
Author   OpenMined
🌐
Sling Academy
slingacademy.com › article › how-to-find-the-intersection-of-2-sets-in-swift
How to Find the Intersection of 2 Sets in Swift - Sling Academy
Swift provides a built-in method called intersection() that can help you painlessly get the intersection of two sets with just a single line of code:
🌐
Linux Hint
linuxhint.com › swift-set-intersection
Swift Set – Intersection()
A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers · Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Medium
medium.com › swift-programming › understanding-collection-types-in-swift-part-2-622ded4b2713
Understanding Collection Types in Swift Part 2 | by Keith Elliott (keithelliott.co) | Swift Programming | Medium
March 13, 2016 - For us, the gist is that Set operations ... With that, let’s dive in. Intersection — The intersect(:) method will return a new set that contains just the values common to both sets....
🌐
Andybargh
andybargh.com › swift-sets
Swift Sets
July 18, 2019 - When called, the intersect(_:) function returns a Set containing those elements that are members of both the set on which the function is called and the set that is supplied as a parameter.