Siesta配置由关闭错误自我捕获'

时间:2018-05-16 12:33:58

标签: swift siesta

我正在使用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)
        }
    }

}

2 个答案:

答案 0 :(得分:1)

您可能希望在闭包开头添加[unowned self],这样就不会保留闭包。请尝试[weak self ]

答案 1 :(得分:0)

错误消息告诉您问题所在:

  

错误:'自我'在所有成员初始化之前由关闭捕获

您尝试在初始化所有成员之前捕获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