Search code examples
iosswiftuilabelclosures

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


Making three separate calls to addSubview() on contentView for an instance of UITableViewCell may be reduced to Swift map(_:):

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

The shorthand, however, throws an error: "Anonymous closure argument not contained in closure". Would .forEach be the best here?


Solution

  • This code is invalid because it's using an anonymous closure argument $0, without being in a closure.

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

    There are two ways to fix this, either 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 either case, you should use forEach rather than map, since you don't care about the (Void) return value of addSubview:

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