jayant
(Jayant)
1
Here's a quick draft pitch before I can expand on it. The gist is to add an index to the functional methods, so it can allow for something like (note mapi is used to differentiate it from map)
let arrayNumbers = [1, 2, 3, 4, 5, 6]
let oddOnes = arrayNumbers.mapi{(number, index) in
if index % 2 == 0 {
return number
} else {
return number * 2
}
}
in case of reduce, filter etc it can be used in a similar fashion where the index helps to eliminate loops that would otherwise look like
let numArray = [1, 2, 3, 4, 5]
var index = 0
for number in numArray {
if index % 5 == 0 {
// do something
}
index += 1
}
Would also appreciate if someone can help creating a proposal on this, I am sure this will be quite useful
thanks,
Jayant
1 Like
ahti
(Lukas Stabe 🙃)
2
You can use Sequence.enumerated() for these use-cases quite easily, so I don't think introducing new versions of the functional methods is worth it.
3 Likes
jayant
(Jayant)
3
Vielen danke @ahti,
but if we were to benchmark the speeds of processing using loops (sequence.enumerated()) vs functional, do they stack up comparable?
Maybe the example of the loop is not well presented, but the point here is about
- functionality - ability to use an index
- speed - achieving it faster/efficiently
if these two are achieved by Sequence.enumerated, then I believe this should work for me.
thanks,
ahti
(Lukas Stabe 🙃)
4
This is the meat of enumerated(). It doesn't do much except incrementing the counter and passing on the value, plus it's mostly inlineable, so I'd assume it would be reasonably fast, but I don't have any numbers to back that up.
(Oh btw, you don't need to use enumerated with loops, you can just as well do something like someSequence.enumerated().map { ... })
4 Likes
Nevin
5
I don’t think we need these methods. It’s trivial to write x.indices.map{ … }, and access the values as needed via subscript.
1 Like
jayant
(Jayant)
7
Thanks @ahti, that works for me, the point is there are so many little details around these. 