我正在使用 Siesta 框架并尝试添加装饰器以便在令牌过期时刷新令牌,但我得到:"在所有成员初始化之前被闭包捕获"。
可能是什么原因?
service.configure("**") {
$0.decorateRequests {
self.refreshTokenOnAuthFailure(request: $1) // this line complains
}
}
更新
我找到了我的问题,想与您分享。该问题与作为类属性的服务有关:
class API: NSObject {
private let service = Service(
baseURL: myApiBaseUrl,
standardTransformers: [.text, .json]
)
override init() {
#if DEBUG
// Bare-bones logging of which network calls Siesta makes:
LogCategory.enabled = [.network]
#endif
service.configure("**") {
$0.headers["Token"] = "Bearer (token)"
$0.headers["Content-Type"] = "application/json"
$0.headers["Accept"] = "application/json"
$0.decorateRequests {
self.refreshTokenOnAuthFailure(request: $1)
}
}
}
我没有使用类属性,而是将服务移到了类之外,并添加了指定的初始值设定项。
init(myService:Service){
super.init()
myService.configure("**") {
$0.headers["Token"] = "Bearer (token)"
$0.headers["Content-Type"] = "application/json"
$0.headers["Accept"] = "application/json"
$0.decorateRequests {
self.refreshTokenOnAuthFailure(request: $1)
}
}
}
您可能希望在闭包的开头添加[unowned self]
,这样就不会保留闭包。也请尝试[weak self ]
错误消息告诉您问题所在:
错误:在所有成员初始化之前,闭包捕获了"self">
您正在尝试捕获初始化所有成员之前的self
。考虑以下两个示例,一个显示您遇到的错误,另一个显示没有。
错误示例
class Customer {
var someProperty: String
var someArray: [Int] = [1,2,3]
init() {
someArray.forEach {
print("($0): (self.someProperty)") // Error: 'self' captured before initializing 'someProperty'
}
someProperty = "Potato"
}
}
_ = Customer()
溶液
class Customer {
var someProperty: String
var someArray: [Int] = [1,2,3]
init() {
someProperty = "Potato"
someArray.forEach {
print("($0): (self.someProperty)") // Good, 'someProperty' has been initialized already
}
}
}
_ = Customer()
// Output:
//
// 1: Potato
// 2: Potato
// 3: Potato