Search code examples
swiftloopsenumeration

Rewite for in 0...n loop by map


I have a swift code like below

var items: [Item] = []
for i in 0...20 {
    items.append( makeItem(atIndex: i) )
}

would it be possible to rewrite above like

var items: [Item] = [0...20].map {
   makeItem(atIndex: i)
}

Solution

  • It's possible, just don't wrap the range in an array, so use (0...20) instead of [0...20]

    You can even pass the name of the function and you won't have to create a closure with a single call.

    let items = (0...20).map(makeItem)