Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How to get indexes of filtered items of array

let items: [String] = ["A", "B", "A", "C", "A", "D"]  items.whatFunction("A") // -> [0, 2, 4] items.whatFunction("B") // -> [1] 

Does Swift 3 support a function like whatFunction(_: Element)?

If not, what is the most efficient logic?

like image 387
Byoth Avatar asked Aug 29 '17 07:08

Byoth


People also ask

How do you get an index of an array in Swift?

To get the first index of an item in an array in Swift, use the array. firstIndex(where:) method. print(i1!)

How do you check if an array contains a value Swift?

It's easy to find out whether an array contains a specific value, because Swift has a contains() method that returns true or false depending on whether that item is found. For example: let array = ["Apples", "Peaches", "Plums"] if array.

What is filter map and reduce in Swift?

In Swift you use map(), reduce() and filter() to loop over collections like arrays and dictionaries, without using a for-loop. The map, reduce and filter functions come from the realm of functional programming (FP). They're called higher-order functions, because they take functions as input.


1 Answers

You can filter the indices of the array directly, it avoids the extra mapping.

let items = ["A", "B", "A", "C", "A", "D"] let filteredIndices = items.indices.filter {items[$0] == "A"} 

or as Array extension:

extension Array where Element: Equatable {      func whatFunction(_ value :  Element) -> [Int] {         return self.indices.filter {self[$0] == value}     }  }  items.whatFunction("A") // -> [0, 2, 4] items.whatFunction("B") // -> [1] 

or still more generic

extension Collection where Element: Equatable {      func whatFunction(_ value :  Element) -> [Index] {         return self.indices.filter {self[$0] == value}     }  } 
like image 174
vadian Avatar answered Sep 21 '22 18:09

vadian