一个在 Swift 中符合人体工程学且安全地捕获和弱化对象的机制。
Without Capture
With Capture
默认
{ [weak self] in
guard let self else { return }
/// ...
}
capture { _self in
/// ...
}
多个参数
{ [weak self] a, b, c in
guard let self else { return }
/// ...
}
capture { _self, a, b, c in
/// ...
}
方法
{ [weak self] in
guard let self = self else { return }
self.someMethod()
}
capture(in: <#Type#>.someMethod)
返回值
let object.dataSource = { [weak self] in
guard let self = self else { return [] }
return self.data
}
let object.dataSource = capture(orReturn: [], in: \.data)
你可以通过将其添加为包依赖项,将 swift-capture
添加到 Xcode 项目中。
"https://github.com/capturecontext/swift-capture"
如果你的项目使用 SwiftPM,你可以将 weak
添加到你的包文件中。我的建议是使用 SSH。
.package(
url: "git@github.com:capturecontext/swift-capture.git",
.upToNextMajor("3.0.0")
)
不要忘记目标依赖项
.product(
name: "Capture",
package: "swift-capture"
)
此库在 MIT 许可证下发布。有关详细信息,请参阅 LICENSE。