简体   繁体   中英

Siesta configuration 'self captured by a closure error'

I am using Siesta framework and trying to add decorator in order to refresh token when it expires but I am getting: 'self captured by a closure before all members were initialized'.

What could be the reason?

service.configure("**") {
      $0.decorateRequests {
      self.refreshTokenOnAuthFailure(request: $1) // this line complains
    }
}

UPDATE

I found my problem and wanted to share it with you. The problem is related to services which were class properties:

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)
       }
    }

}

Instead of using a class property, I moved my service outside of the class and added a designated initializer.

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)
        }
    }

}

You might wanna add [unowned self] at the beginning of the closure that way the the closure is not retained. Please try [weak self ] also

The error message is telling you what the problem is:

error: 'self' captured by a closure before all members were initialized

You are trying to capture self before all members were initialized. Consider the following two examples, one shows the error you are having and the other doesn't.

Example of your error

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()

Solution

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM