Reputation: 3803
I am new to swift. I wrote a method to find matched items in an array. But I am using a simple for loop. I am thinking is there any way we can use map for this kind of operation.
var matchedCompanyIds : Set<String> = []
for company in editableStaticUserData.companies {
if let companyIdentifier : String = company.companiesIdentifier {
if let companyIds = self.editableFilter?.companyIds {
if companyIds.contains(companyIdentifier) {
matchedCompanyIds.insert(companyIdentifier)
}
}
}
}
Upvotes: 1
Views: 1773
Reputation: 4930
Sorry for my comment, I did not read your code. I would do like this
let identifiers = companies.flatMap({$0.companiesIdentifier})
let result = companyIds?.intersect(identifiers)
the result is optional but it is almost the same thing
Upvotes: 3
Reputation: 12324
I think the function you are looking for is filter. The map function is used to perform some action on each element of an array and then assign the result to a new array. So when you use the map function, the resulting array will be the same capacity as the array being mapped. Filter, however, is used to find items in an array that fit a boolean criteria. When using the filter function, the resulting array can be any capacity from 0
to arrayToFilter.count
.
Applying the filter function to reduce your for-loop would look like this. The $0
will be the company
object from editableStaticUserData.companies
as the filter func iterates over that array (similar to your for-loop).
let filteredArray = editableStaticUserData.companies.filter {
if let companyIdentifier = $0.companiesIdentifier,
let companyIds = self.editableFilter?.companyIds,
where companyIds.contains(companyIdentifier) {
return true
}
}
var matchedCompanyIds = Set(filteredArray)
I apologize if there is syntax errors in the code; I did this off the top of my head.
Upvotes: 3