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?
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?
you can use it like that :
For example finding the indices of p_last values that are in inds1 array: (swift 4+)
idx1 = [0,1]
You can filter the
indices
of the array directly, it avoids the extramap
ping.or as
Array
extension:or still more generic
In Swift 3 and Swift 4 you can do that:
I hope my answer was helpful
You can create your own extension for arrays.
You can simply call it like this
You can achieve this by chain of:
enumerated()
- add indexes;filter()
out unnecessary items;map()
our indexes.Example (works in Swift 3 - Swift 4.x):
Another way is using
flatMap
, which allows you to check the element and return index if needed in one closure.Example (works in Swift 3 - Swift 4.0):
But since Swift 4.1
flatMap
that can return non-nil objects become deprecated and instead you should usecompactMap
.Example (works since Swift 4.1):
And the cleanest and the most memory-cheap way is to iterate through array indices and check if element of array at current index equals to required element.
Example (works in Swift 3 - Swift 4.x):