Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two arrays in swift and removing elements with specific fields that don't match

Tags:

ios

swift

I have two arrays:

var packages = [SAPackage]()
var inappProducts = [SKProduct]()

The SAPackage object in the packages array has a String var titled sku. TheSKProduct object in the inappProducts array has a String var titled productIdentifier. What I want to do is remove any object in the packages array that doesn't have a sku String that matches any objects productIdentifier String in the inappProducts array. Is there anyway to go about this? Thought about using sets to find an intersection however I cannot examine individual object fields doing this just whole objects. Any pointers on this would be greatly appreciated!

like image 819
Kex Avatar asked Dec 05 '22 18:12

Kex


1 Answers

You can use this code to filter those packages whose "sku" exist in inappProducts, SKProducts,

let filteredPackages = packages.filter { package in
    return inappProducts.contains { product in
        product.productIdentifier == package.sku
    }
}
like image 193
Sandeep Avatar answered May 21 '23 17:05

Sandeep