The index
is not used at all, therefore you do not need enumerate()
:
for point in self.points { ... }
(You mentioned in a comment that the index is used somewhere else,
but we can review only the code that is shown in your question.)
let pointButton = UIButton()
pointButton.frame = point.bounds
can be simplified to
let pointButton = UIButton(frame: point.bounds)
and then you could get rid of the intermediate variable:
for point in self.points {
self.view.addSubview(UIButton(frame: point.bounds))
}
and this looks like the best solution in your case to me.
You could use map()
for that purpose:
self.points.map {
self.view.addSubview(UIButton(frame: $0.bounds))
}
But using map()
for its side effects is frowned-upon, see for example
Higher order function: “Cannot invoke 'map' with an argument list of type '((_) -> _)'”,
where an explicit foreach
method is offered as an alternative:
extension Array {
func foreach(function: T -> ()) {
for elem in self {
function(elem)
}
}
}
which can be used as
self.points.foreach {
self.view.addSubview(UIButton(frame: $0.bounds))
}
self.view.addSubview()
removes any point of doing so because that is a side-effect. I don't know enough Swift to write this out, but you would want to usemap
over theself.points
collection and have it return yourpointButton
, and then the mapped array as subviews. \$\endgroup\$self.view.addSubview()
in the function, you are causing a side effect because you are modifying the outside world (self.view.addSubview()
stores state). Obviously every useful program uses state, but using map "just because" doesn't make it FP because of the reasons I've mentioned. \$\endgroup\$enumerate
if you're not using the index? \$\endgroup\$