PHBApplying
这是什么?
应用 只是一个语法糖。这是一个将给定闭包应用到接收对象上的方法;例如
let nameLabel = UILabel.applying { $0.text = viewModel.name }
应用 使用起来非常简洁的初始化代码。而不是
private lazy var button: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(onTap), for: .touchUpInside)
return button
}()
我们可以这样写
private lazy var button = UIButton()
.applying { $0.addTarget(self, action: #selector(onTap), for: .touchUpInside) }
它与 Then 概念上相同,只是使用了不同的术语。我选择使用 applying
是因为
then
适合描述异步过程,并且通常用于该环境中apply
在 Kotlin 中表示的意义与这个库中的意义完全相同,因此它是一个已建立的术语applying
表明该方法会修改并返回接收器,这与类似的 Swift 术语(如sorted
)保持一致。
请注意,我独立地产生了与 Then 相同的想法。我的原始用例促使我将其命名为 Configurable(请参阅我的 Medium 文章 这里)。我为我的工作项目开发了它,并在我参与不同的项目时发现自己非常怀念它,所以我决定将其作为一个 pod 发布。
示例
要运行示例项目,先复制仓库,然后从示例目录运行 pod install
需求
安装
Swift Package Manager
PHBApplying可以通过SPM安装。将其添加到依赖项中
// ...
dependencies: [
.package(url: "https://github.com/phlippieb/PHBApplying.git", from: "0.2.1")
],
targets: [
.target(name: "YourTarget", dependencies: ["PHBApplying"])
],
// ...
Cocoapods
PHBApplying在CocoaPods中可用。要安装它,只需将以下行添加到您的Podfile中
pod 'PHBApplying', '~> 0.2.1'
作者
phlippieb, [email protected]
许可
PHBApplying遵循MIT许可。有关更多信息,请参阅LICENSE文件。