【发布时间】:2020-08-29 17:35:03
【问题描述】:
我在检查代码时确实找到了以下代码:
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return super.layoutAttributesForElements(in: rect)?
.compactMap { $0.copy() as? ParallaxLayoutAttributes }
.compactMap(prepareAttributes)
}
private func prepareAttributes(attributes: ParallaxLayoutAttributes) -> ParallaxLayoutAttributes {
// Lot of code doing stuff with attributes
return attributes
}
所以,实际上我想问的是,compact 函数声明如下:
@inlinable public func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
在此示例中,我们只传递函数,不带参数:
.compactMap(prepareAttributes)
这完全颠覆了我的想法,因为,prepareAttributes 函数声明是这样的(你必须通过参数):
private func prepareAttributes(attributes: ParallaxLayoutAttributes) -> ParallaxLayoutAttributes
那么,为什么上面的代码可以编译,.compactMap(prepareAttributes) 到底是怎么编译的?
当您没有为 prepareAttributes 函数传递参数时运行?
【问题讨论】:
-
相关(如果不重复):stackoverflow.com/q/37493802/1187415.
标签: swift higher-order-functions