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?
To get the first index of an item in an array in Swift, use the array. firstIndex(where:) method. print(i1!)
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.
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.
You can filter the indices
of the array directly, it avoids the extra map
ping.
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} } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With