对
contentView
上的addSubview()
进行三次单独的调用,可以简化为UITableViewCell
的实例,可以简化为 Swift map(_:)
:
[nameLabel, numberLabel, informationLabel].map(contentView.addSubview($0))
但是,速记会抛出一个错误:"匿名闭包参数不包含在闭包中"。.forEach
会是这里最好的吗?
此代码无效,因为它使用匿名闭包参数 $0
,而不在闭包中。
[nameLabel, numberLabel, informationLabel].map(contentView.addSubview($0))
有两种方法可以解决此问题,要么将其放在闭包中:
[nameLabel, numberLabel, informationLabel].map { contentView.addSubview($0) }
或者更好的是,直接使用实例方法:
[nameLabel, numberLabel, informationLabel].map(contentView.addSubview)
无论哪种情况,你都应该使用 forEach
而不是 map
,因为你不关心 addSubview
的 (Void
( 返回值:
[nameLabel, numberLabel, informationLabel].forEach(contentView.addSubview)
当闭包返回 void 时使用 .forEach
[nameLabel, numberLabel, informationLabel].forEach { contentView.addSubview($0) }