Use block in Swift giving error "Variable used within its own initial value"
The Swift compiler is very strict and checks that every variable has
a defined value before it is used. The compiler
does not know that in your case, the closures will be executed only
after the requestReference
variable is defined.
In such cases you can use an implicitly unwrapped optional:
var requestReference: String!
requestReference = self.operation(..., success: {(_ task: URLSessionDataTask, _ responseObject: Any) -> Void in
// ...
delegate.request(with: requestReference, didFinishWithBusinessError: error)
}, failure: {(_ task: URLSessionDataTask, _ error: Error) -> Void in
delegate.request(with: requestReference, didFailWithError: error)
})
An implicitly unwrapped optional is a promise to the compiler: The variable has no value now, but it will have a value when it is used.