我正在开发一个 iOS 应用程序,它的基础是带有 AFNetworking 的 Objective-C,用于与 API 通信。现在我正在用 Swift 编写新的 ViewControllers,但 Swift 文件中的 CompletionBlock 有一些问题。
原始的 Objective-C 代码:
- (void)downloadJson {
[[ODDWebService sharedInstance] getParkingSpacesWithCompletionBlock:^(NSArray *result, BOOL succes) {
if(succes) {
[self.parkings removeAllObjects];
for(NSDictionary *dict in result) {
Parking *parking = [[Parking alloc] init];
parking.name = [dict objectForKey:@"name"];
parking.freespace = [[dict objectForKey:@"freespace"] integerValue];
[self.parkings addObject:parking];
}
[self updateParkings];
} else {
NSLog(@"ERROR RETRIEVING PARKING SPACES");
}
}];
}
这是我认为在 Swift 中应该是这样的:
func downloadJson() {
ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { (result: AnyObject, succes: Bool) -> Void in
if(succes) {
self.parkings.removeAllObjects()
for dict: NSDictionary in result {
var parking: Parking = Parking
parking.name = dict["name"]
parking.freespace = dict["freespace"].integerValue()
parkings.addObject(parking)
} else {
NSLog("ERROR RETRIEVING PARKING SPACES")
}
}
}
}
主要错误在第二行代码:
'(AnyObject, Bool) -> Void' is not convertible to '(([AnyObject]!, Bool) -> Void)!'
最佳答案
替换
func downloadJson() {
ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { (result: AnyObject, succes: Bool) -> Void in
if(succes) {
与
func downloadJson() {
ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock {
result, success in
if(succes) {
还将以下代码中的第一行添加到您的代码中。
if let dicts = result as? NSDictionary<String, AnyObject> {
for dict: NSDictionary in dicts {
var parking: Parking = Parking
parking.name = dict["name"]
关于ios - Swift 中的完成 block AFNetworking,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32690703/