subviews.forEach(view.addSubview) — Swift

--

#FirstClassFunctions

Below, ‘subviews’ is an array of simple UIViews.

How is subviews.forEach(view.addSubview) possible?

subviews.forEach(view.addSubview)

view.addSubview accepts a UIView.

forEach passes 1 subview at each iteration.

Swift lets us take advantage of the concept ‘first class functions.’

First class functions let us pass functions (& initializers) to other functions.

For each of subviews’ view, view.addSubview passes a @non-escaping closure of type (UIView) →(Void) to the forEach method.

The forEach method invokes each closure, & returns 1 of subviews’ UIViews into the closure during each iteration of the forEach loop. The UIView is received by view.addSubview.

REMINDER:

Lookout for retain cycles when the function you pass to a function is an @escaping closure.

--

--

Javid Poornasir
Javid Poornasir

Written by Javid Poornasir

I generally focus on iOS technologies. Here are some of my notes.

No responses yet