If you came to iOS development from the realms of Ruby or jQuery-inflected Javascript, you were probably happy to see enumerator methods like map, filter, and reduce show up in Swift. But hang on – what about this one?

arr = [1, 2, 3, 4, 5]
arr.each { |a| print a -= 10, " " }
> > -9 -8 -7 -6 -5

Ruby describes the each method this way:

In case of Array’s each, all elements in the Array instance are yielded to the supplied block in sequence.

Hmmm. So it calls a block (closure) with each element of the array in sequence. Doesn’t that sounds an awful lot like… map?

let arr = [1, 2, 3, 4, 5]
arr.map { a in print("\(a - 10) ") }
> > -9 -8 -7 -6 -5

Cool. When called this way, map infers that the return type of the closure is Void, builds an array of Void from the elements in the array, and then throws it out since it isn’t stored in another variable. The compiler might even be savvy enough to know that it doesn’t need space for the resulting array and skip that step.

How is that any better than a for...in loop? Well, closures don’t need to be defined inline – they can be stored in a variable or passed as a parameter to a function. For example, if you need to reset different groups of text fields in your view controller at different times, you could do that by writing a closure to update a text field and then passing that to map for the group you need to reset:

// define closure once
let resetTextField = {
        (textField: UITextField) -> () in
        textField.textColor = UIColor.lightGrayColor()
        textField.text = "tap to edit"

// use it in somewhere else on an Array of UITextFields