Reputation: 2275
I'm writing a new subclass of UIView using swift. I want to have an array of views, and I want to instantiate them in the initial declaration, for clarity.
If this was an Int array, I could do something like this:
let values: [Int] = (0...4).map() { $0 }
and so I'm trying to come up with some sort of similarly swifty one-liner that will create an array of UIButtons, instead of Ints.
my first thought was (0...4).map() { UIButton.buttonWithType(.Custom) }
but if I do this (or if I replace the UIButton code with, say NSObject()) I get an error saying that "'Transition' does not have a member named 'map'". I can, say, do map() { "\($0)" }
and get an array of strings.
My next thought was just to get an array of ints first, and then use map on those to return buttons, like:
let values: [UIButton] = (0...4)
.map() { $0 }
.map() { UIButton.buttonWithType(.Custom) }
but this gives me the same error. What am I doing wrong, here?
Upvotes: 2
Views: 2175
Reputation: 2275
Okay, the solution came to me pretty quickly: I guess I can't quietly ignore the variable of the closure I'm passing in to the map function; I need to ignore it explicitly. So to get my array of 4 buttons, I can use an _ in the map function, like this:
var buttons = (0...4).map() {_ in UIButton.buttonWithType(.Custom) }
or what I actually ended up using:
lazy var buttons: [UIButton] = (0...4).map() { _ in
let button = UIButton.buttonWithType(.Custom) as UIButton
self.addSubview(button)
return button
}
Upvotes: 4