[swift-evolution] [Pitch] Enumerate from offset
jaden.geller at gmail.com
jaden.geller at gmail.com
Thu May 4 12:15:59 CDT 2017
It's been suggested by a core team member that enumerated itself might not hold its weight in the standard library. Instead, we ought to write `zip(foo.indices, foo)` or `zip(0..., foo)`. It's easier for the caller to see which side of the tuple stores the index and whether the index is an integer or an actual index type. This use case seems to further support this design since `zip(x…, foo)` and `zip(foo.indicies.drop(x), foo)` can be easily written.
> On May 4, 2017, at 8:50 AM, BJ Homer via swift-evolution <swift-evolution at swift.org> wrote:
>
>> On May 4, 2017, at 8:51 AM, André Videla via swift-evolution <swift-evolution at swift.org> wrote:
>>
>> You can do this trivially with drop. But enumerated from has one nice property:
>>
>> myArray.enumerated().dropFirst(6) // counts from 6
>>
>> myArray.dropFirst(6).enumerated() // counts from 0
>>
>> Those two lines do very different things even though they look similar
>
> Neither of those does what the proposed enumerated(from:) does, if I understand correctly:
>
> let a = [1, 2, 3, 4, 5]
> let result = a.enumerated().dropFirst(2)
> /*
> (offset: 2, element: 3)
> (offset: 3, element: 4)
> (offset: 4, element: 5)
>
> */
>
> let result2 = a.dropFirst(2).enumerated()
> /*
> (offset: 0, element: 3)
> (offset: 1, element: 4)
> (offset: 2, element: 5)
> */
>
>
> let proposed = a.enumerated(from: 2)
> /*
> (offset: 2, element: 1)
> (offset: 3, element: 2)
> (offset: 4, element: 3)
> (offset: 5, element: 4)
> (offset: 6, element: 5)
> */
> The enumerated(from:) name is not clear; it reads (to me) like it’s going to enumerate elements starting at the Nth element. What it actually does (as proposed) is start counting at N, instead of counting at 0.
>
> I’m not convinced this is a valuable addition to the language. The use cases are not widely applicable, and if you need it it’s easy to get the same results in a way that avoids the confusion.
>
> let a = [1, 2, 3, 4, 5]
>
> let result = a.enumerated().map { (idx, element) in
> return (idx+2, element)
> }
>
> // OR
>
> for (idx, element) in a.enumerated() {
> let offsetIndex = idx + 2
> // Use offsetIndex how you will
> }
>
>
> -BJ
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170504/aef58c0f/attachment.html>
More information about the swift-evolution
mailing list