在Objective-C中,您可以定义块的输入和输出,存储传递给方法的其中一个块,然后再使用该块:
// in .h
typedef void (^APLCalibrationProgressHandler)(float percentComplete);
typedef void (^APLCalibrationCompletionHandler)(NSInteger measuredPower, NSError *error);
// in .m
@property (strong) APLCalibrationProgressHandler progressHandler;
@property (strong) APLCalibrationCompletionHandler completionHandler;
- (id)initWithRegion:(CLBeaconRegion *)region completionHandler:(APLCalibrationCompletionHandler)handler
{
self = [super init];
if(self)
{
...
_completionHandler = [handler copy];
..
}
return self;
}
- (void)performCalibrationWithProgressHandler:(APLCalibrationProgressHandler)handler
{
...
self.progressHandler = [handler copy];
...
dispatch_async(dispatch_get_main_queue(), ^{
_completionHandler(0, error);
});
...
}
Run Code Online (Sandbox Code Playgroud)
所以我试图在Swift中做等效的事情:
var completionHandler:(Float)->Void={}
init() {
locationManager = CLLocationManager()
region = CLBeaconRegion()
timer = NSTimer()
}
convenience init(region: CLBeaconRegion, …Run Code Online (Sandbox Code Playgroud) 我们可以在Objective-C中声明如下所示的块.
typedef void (^CompletionBlock) (NSString* completionReason);
Run Code Online (Sandbox Code Playgroud)
我试图在swift中做到这一点,它给出了错误.
func completionFunction(NSString* completionReason){ }
typealias CompletionBlock = completionFunction
Run Code Online (Sandbox Code Playgroud)
错误:使用未声明的'completionFunction'
定义:
var completion: CompletionBlock = { }
Run Code Online (Sandbox Code Playgroud)
这该怎么做?
更新:
根据@ jtbandes的回答,我可以创建具有多个参数的闭包
typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()
Run Code Online (Sandbox Code Playgroud) 在 Objective-C 中,我使用了对现在必须转换为 Swift 的完成块的处理:
在DetailDisplayController.h
typedef void (^AddedCompletitionBlock)(BOOL saved, NSString *primarykey, NSUInteger recordCount);
@interface DetailDisplayController : UITableViewController
@property (nonatomic, copy) AddedCompletitionBlock completionBlock;
@property (strong, nonatomic) Details *detail;
Run Code Online (Sandbox Code Playgroud)
在DetailDisplayController.m
- (void) saveClicked:(id)sender
{
// retrieve PK
NSString *objectId = [[[_detail objectID] URIRepresentation] absoluteString];
if (self.completionBlock != nil)
{
self.completionBlock(_rowChanged, objectId, [_fetchedResultsController.fetchedObjects count]);
}
Run Code Online (Sandbox Code Playgroud)
_rowChanged 和 _fetchedResultsController 是实例变量
在DetailViewController.m调用类中,使用了传递的块
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"DetailDisplay"])
{
DetailDisplayController *detailDisplayController = segue.destinationViewController;
...
detailDisplayController.completionBlock = ^(BOOL saved, …Run Code Online (Sandbox Code Playgroud)