Using [weak self-government] and assignment in closing Swift

I played with Swift and included AFNetworking in the project and got some code that I don't really like.

already posted on Apple dev forums and got no response, I thought I would bring it to SO ...

My class has a strong reference to the instance AFHTTPSessionManager, and the next snippet is the closure used when calling the method GET(_, parameters, success, failure).

let failure = { [weak self] (task: NSURLSessionDataTask!, error: NSError!) -> (Void) in
    if error?.userInfo[AFNetworkingOperationFailingURLResponseErrorKey]?.statusCode == 401 {
        if let weakSelf = self {
            weakSelf.error = NSError(domain: MyConnectionErrorDomain, code: ErrorCode.InvalidCredentials.toRaw(), userInfo: nil)
            weakSelf.state = .Error
        }
    }
}

Is this use case [weak self]in closure along with syntax if letcorrect when I need to mutate errorand variables state self? I suppose this is possible, as it selfmay disappear before the closure is completed. I cannot use self?.error = ...as this gives a compiler error.

+4
1

Xcode 6 beta 5 . , :

if (self?.error = NSError(domain: MyConnectionErrorDomain, code: ErrorCode.InvalidCredentials.toRaw(), userInfo: nil)) == nil {
    // `self` became nil in the meantime
}

: if var , , - 5:

if var strongSelf = self {
    // ...
}
+3

Source: https://habr.com/ru/post/1543900/


All Articles