You’ve got it. You can think of map as the name for a particular and common type for for loop: one that transforms every element of a sequence into something else. In my opinion, when you need to disregard the elements (with an underscore), that’s when map and for both become a little less clear. And in this case, removing nesting isn’t really possible – you can only exchange one method of iteration for the other.
What we really need in this case is just an iterator. (In Swift, that powers a for-in loop. ) Unfortunately, iterators aren’t commonly needed enough to have warranted bringing up earlier in the learning path. I’m thinking maybe that we should introduce the idea here, and let viewers go explore that documentation I linked to, if they’re interested.
Here’s what the change would look like. I think you’ve got a great understanding of this now, so please let me know if you have a suggestion which you think would be clearer!
let squareGridDimensionIterator = subviews.makeIterator()
for subview in subviews as! [UIStackView] {
for _ in squareGridDimensionIterator {
let cardView =
nib.instantiate(withOwner: owner).first { $0 is FrontCardView }
as! FrontCardView
subview.addArrangedSubview(cardView)
}
}
Also, you may be interested in the indices property. It removes the need to manually define 1...subviews.count or 0..<subviews.count.