Search code examples
objective-cswiftblock

Block from Objective-C to Swift


I used a framework Objective-C in my Project (Swift). But in the code have a Block, i cannot convert to swift (i'm newbie in swift) So the code is

[self.datePicker setDateHasItemsCallback:^BOOL(NSDate *date) {
    int tmp = (arc4random() % 30)+1;
    return (tmp % 5 == 0);
}];

Please help me. Thank you ,


Solution

  • Where you would use a block in Objective-C, you use a function in Swift. In Objective-C, the argument is a block that takes an NSDate and returns a BOOL:

    [self.datePicker setDateHasItemsCallback:^BOOL(NSDate *date) {
    

    So, in Swift the argument is a function that takes an NSDate and returns a Bool:

    self.datePicker.setDateHasItemsCallback {
        (date:NSDate) -> Bool in
        return true // fix this up as desired
    }