How to determine if one array contains all elements of another array in Swift?
I have 2 arrays:
var list:Array<Int> = [1,2,3,4,5]
var findList:Array<Int> = [1,3,5]
I want to determine if list
Array contains all findList
elements.
By the way, elements might be String
as well or other type.
How to do that?
I know that Swift provides contains
method that works with one item.
Solution 1:
Instead of iterating through arrays and doing filtering yourself, you can use NSSet
to do all the work for you.
var list:Array<Int> = [1,2,3,4,5]
var findList:Array<Int> = [1,3,5]
let listSet = NSSet(array: list)
let findListSet = NSSet(array: findList)
let allElemtsEqual = findListSet.isSubsetOfSet(otherSet: listSet)
NSSet
is a lot faster than arrays at checking if it contains any object. In fact it's what it's designed for.
Edit: Using Swift's built-in Set
.
let list = [1,2,3,4,5]
let findList = [1,3,5]
let listSet = Set(list)
let findListSet = Set(findList)
//**Swift 4.2 and Above**
let allElemsContained = findListSet.isSubset(of: listSet)
//below versions
//let allElemsContained = findListSet.isSubsetOf(listSet)
Solution 2:
allSatisfy
seems to be what you want, assuming you can't conform your elements to Hashable
and use the set intersection approach others have mentioned:
let containsAll = subArray.allSatisfy(largerArray.contains)