In terms of Swift and sleep depravation1, neither one is good for the other. I asked here: “But why does the first one work?” in reference to:
print([1, 2, 3, 4, 5, 6].map(String.init)) print([1, 2, 3, 4, 5, 6].map{String($0)})
Now I’m going to answer in a way that I should probably have managed on the first go-round. Thanks to everyone who pinged me. First, String.init is a function. For example, this
func plus1(a : Int) -> Int {return a + 1}
creates a function called plus1. If you type plus1 into a playground, it shows the Int-> Int signature.
You can assign plus1 to something else and that’s a function too.
let plusOne = plus1 print([1, 2, 3, 4, 5, 6].map(plus1)) print([1, 2, 3, 4, 5, 6].map(plusOne))
The map function takes one argument, a function / closure / lambda expression / thing that does things, and returns an array with result of mapping that transformation over each element of self.
This example uses a closure. It is an argument to the map function.
print([1, 2, 3, 4, 5, 6].map({$0 + 1}))
Because the closure is the last argument, you theoretically don’t have to use parentheses.
print([1, 2, 3, 4, 5, 6].map{$0 + 1})
As I’m starting to learn, it’s a better idea to keep those parens. Map uses values returned by its closure parameter. Naked-trailing-closure is better suited for situations where the closure executes as a procedure rather than a function, for example GCD dispatch.
So the example I started out with:
print([1, 2, 3, 4, 5, 6].map{String($0)})
would be better implemented as
debugPrint([1, 2, 3, 4, 5, 6].map({String($0)}))
Finally, there is a related construct, which has nothing to do with this, which I was incoherently mumbling about last week, which goes like this:
MyClass.myMethod(instance)
This is a curried function on a class, that enables you to pass MyClass.myMethod as a closure, and can be used for storing target-action patterns. Thanks, Thompas Pelaia, who adds, “A big advantage over the Objective-C target-action using selectors is that you get compile time checking in Swift. For example, you can use it with protocols and/or generics.”
Me? I’m going to try to get some sleep this week. Hopefully no more tornados.
p.s. A big thanks to Chris Lattner
Comments are closed.