Use block in Swift giving error “Variable used within its own initial value”

℡╲_俬逩灬. 提交于 2019-12-12 11:14:10

问题


This is my code in obj-c:

__block NSString *requestReference = [self operation:method url:url parameters:parameters headers:headers success:^(NSURLSessionDataTask *task, id responseObject) {
NSError *error = [NSError errorWithSessionTask:task responseObject:responseObject];
if (error) {
    NSLog(@"error - %@", error);
    [delegate requestWithReference:requestReference didFinishWithBusinessError:error];
} else {
    id responseModel;
    if (modelClass && responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            // if response is a dictionary, create model out of it
            responseModel = [modelClass objectFromDictionary:responseObject error:&error];
        } else if ([responseObject isKindOfClass:[NSArray class]]) {
        }
    }
} } failure:^(NSURLSessionDataTask *task, NSError *error) {
[delegate requestWithReference:requestReference didFailWithError:error]; }];

and this is the code after conversion in Swift:

var requestReference = self.operation(method, url: url, parameters: parameters, headers: headers, success: {(_ task: URLSessionDataTask, _ responseObject: Any) -> Void in
    var error = Error(sessionTask: task, responseObject: responseObject)
    if error {
        print("error - \(error)")
        delegate.request(with: requestReference, didFinishWithBusinessError: error)
    }
    else {
        var responseModel: Any!
        if modelClass && responseObject {
            if (responseObject is [AnyHashable: Any]) {
                // if response is a dictionary, create model out of it
                do {
                    responseModel = try modelClass.object(fromDictionary: responseObject)
                }
                catch {
                }
            }
            else if (responseObject is [Any]) {

            }
        }
    }
}, failure: {(_ task: URLSessionDataTask, _ error: Error) -> Void in
    delegate.request(with: requestReference, didFailWithError: error)
})

I have converted and come up with this code. everything is working in this code But I'm getting error:

"Variable used within its own initial value"


回答1:


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.




回答2:


Define it first, then use it:

var requestReference = ""
requestReference = self.operation...


来源:https://stackoverflow.com/questions/41285496/use-block-in-swift-giving-error-variable-used-within-its-own-initial-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!