我正在研究iOS應用程序,其基礎是Objective-C與AFNetworking與API進行通信。現在我在Swift中編寫新的ViewControllers,並且在Swift文件中的CompletionBlock中遇到了一些問題。完成塊AFNetworking在Swift
原來的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");
}
}];
}
這是我認爲它應該是在斯威夫特:
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)!'
只需添加「!」在任何對象之後ODDWebService.sharedInstance()。getParkingSpacesWithCompletionBlock {(result:AnyObject!,succes:Bool) - >無效 –
當我這樣做,ViewController中的錯誤消失,但我得到一個命令失敗,由於信號:分段錯誤:11. – Ruben