在通过 Paul Hudsons 的教程学习 Swift 时,我遇到了一些奇怪的事情。
UICollectionViewDiffableDataSource 的初始化器定义为:
public init(collectionView: UICollectionView, cellProvider: @escaping UICollectionViewDiffableDataSource<SectionIdentifierType, ItemIdentifierType>.CellProvider)
据我所知,没有其他初始化程序。然而,Paul 像这样成功地初始化它,省略了 cellProvider 参数:
dataSource = UICollectionViewDiffableDataSource<Section, App>(collectionView: collectionView) { collectionView, indexPath, app in
switch self.sections[indexPath.section].type {
case "mediumTable":
return self.configure(MediumTableCell.self, with: app, for: indexPath)
case "smallTable":
return self.configure(SmallTableCell.self, with: app, for: indexPath)
default:
return self.configure(FeaturedCell.self, with: app, for: indexPath)
}
}
同时,Ray Wenderlich 的教程会这样做:
dataSource = UICollectionViewDiffableDataSource<Section, App>(collectionView: collectionView, cellProvider: { (collectionView, indexPath, app) -> UICollectionViewCell? in
switch self.sections[indexPath.section].type {
case "mediumTable":
return self.configure(MediumTableCell.self, with: app, for: indexPath)
case "smallTable":
return self.configure(SmallTableCell.self, with: app, for: indexPath)
default:
return self.configure(FeaturedCell.self, with: app, for: indexPath)
}
})
我试图了解 Paul 的方式背后发生了什么样的 Swift “魔法”,因为他似乎放弃了 cellProvider 参数,而是做了一些时髦的闭包事情。他在这里应用了哪些 Swift 规则?