[swift-evolution] [Pitch] Enumerate from offset

BJ Homer bjhomer at gmail.com
Thu May 4 10:50:06 CDT 2017


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170504/8b0031a9/attachment.html>


More information about the swift-evolution mailing list