Use a block in Swift, giving the error "Variable used within its initial value"

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 converting to 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 converted and came up with this code. everything works in this code, but I get an error:

"Variable used within its initial value"

+5
source share
2 answers

The Swift compiler is very strict and checks that each variable has a specific value before using it. The compiler does not know that in your case, closing will only be done after the requestReference variable is requestReference .

In such cases, you can use the implicitly expanded option:

 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 expanded option is a promise to the compiler: Now the variable does not matter, but it will matter when used.

+7
source

Define it first, then use:

 var requestReference = "" requestReference = self.operation... 
0
source

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


All Articles