arraysswift3nspredicateeditor

i want array filter array by NSPredicate of swift3.0


I have a need right now, This requirement is to use an array of data in another array filter with NSPredicate. In Object-C it is works like below:

NSArray * arr1 = @[@1,@2,@3]; 

NSArray * arr2 = @[@2,@3,@4,@5];

NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",arr1]; 

NSArray * filter = [arr2 filteredArrayUsingPredicate:filterPredicate]; 

By this method, I can get filter,T he elements in this array are not included in the arr1.But I can't find related methods on Swift 3.0. If I can get all of help,I would appreciate it very much


Solution

  • For that you can simply use filter no need to use NSPredicate.

    let array1 = [1,2,3]
    let array2 = [2,3,4,5]
    let filterArray = array2.filter { !array1.contains($0) }
    print(filterArray) // [4, 5]
    

    Edit: As @Alexander suggested batter if you use set also with array1.

    let array1 = [1,2,3,2,3]
    let set = Set(array1)
    let array2 = [2,3,4,5]
    let filterArray = array2.filter { !set.contains($0) }
    print(filterArray)