How to determine if one array contains all elements of another array in Swift?

后端 未结 12 1131
梦如初夏
梦如初夏 2020-12-13 17:47

I have 2 arrays:

var list:Array = [1,2,3,4,5]
var findList:Array = [1,3,5]

I want to determine if list A

12条回答
  •  借酒劲吻你
    2020-12-13 18:11

    You can use the filter method to return all elements of findList which are not in list:

    let notFoundList = findList.filter( { contains(list, $0) == false } )
    

    then check if the length of the returned array is zero:

    let contained = notFoundList.count == 0
    

    Note that his solution traverses the entire findList array, so it doesn't stop as soon as a non contained element is found. It should be used if you also want to know which elements are not contained.

    If you just need a boolean stating whether all elements are contained or not, then the solution provided by Maxim Shoustin is more efficient.

提交回复
热议问题