Swift map on UILabel "Anonymous closure argument not contained in closure"

Perform three individual calls addSubview()

on contentView

for instance UITableViewCell

may be reduced to Swift map(_:)

:

[nameLabel, numberLabel, informationLabel].map(contentView.addSubview($0))

      

The abbreviation, however, raises the error: "Anonymous closure argument is not contained in closure." Will .forEach

be the best here?

+3


source to share


2 answers


This code is not valid because it uses the anonymous closure argument $0

without being in the closure.

[nameLabel, numberLabel, informationLabel].map(contentView.addSubview($0))

      

There are two ways to fix this, or to put it in a closure:

[nameLabel, numberLabel, informationLabel].map{ contentView.addSubview($0) }

      



Or better yet, just use the instance method directly:

[nameLabel, numberLabel, informationLabel].map(contentView.addSubview)

      

In any case, you should use forEach

, not map

as you don't need to return a value ( Void

) addSubview

:

 [nameLabel, numberLabel, informationLabel].forEach(contentView.addSubview)

      

+4


source


Use .forEach when closure returns void



 [nameLabel, numberLabel, informationLabel].forEach { contentView.addSubview($0) }

      

+2


source







All Articles