一种在 Swift 中安全捕获和弱化对象的机制。
Without weak
With weak
默认
{ [weak self] in
guard let self = self else { return }
/// ...
}
capture { _self in
/// ...
}
多个参数
{ [weak self] a, b, c in
guard let self = self else { return }
/// ...
}
capture { _self, a, b, c in
/// ...
}
方法
{ [weak self] in
guard let self = self else { return }
self.someMethod()
}
capture(in: Self.someMethod)
返回值
let object.dataSource = { [weak self] in
guard let self = self else { return [] }
return self.data
}
let object.dataSource = capture(or: [], in: \.data)
你可以通过将 weak
添加为包依赖项来将其添加到 Xcode 项目中。
"https://github.com/makeupstdio/weak"
如果你的项目使用 SwiftPM,你可以将 weak
添加到你的 package 文件中。我的建议是使用 SSH。
.package(
name: "weak",
url: "git@github.com:makeupstudio/weak.git",
.branch("main")
)
不要忘记目标依赖项
.product(
name: "Weak",
package: "weak"
)
该库是在 MIT 许可证下发布的。有关详细信息,请参阅 LICENSE。