0

I'm recently started working on swift. Here i'm facing the problem with blocks so please help to do this.

Class 1:

I'm using block in Objective-C like this:

typedef void (^AHServicesCallsWrapperBlock)(id, NSError *);

declaration of block variable:

@property (nonatomic, copy) AHServicesCallsWrapperBlock webServiceWrapperBlockHandler;

and passing block a value

self.webServiceWrapperBlockHandler([graphData objectForKey:@"data"], nil);

In Class 2: And i'm using this block in another view controller like:

AHServiceCallWrapper *webServicesCallsWrapper = [[AHServiceCallWrapper alloc] init];
webServicesCallsWrapper.webServiceWrapperBlockHandler = ^(id response, NSError *error)
{
     // do stuff
}

so how can we do this in swift...

2
  • look up closures in swift. there are quite a good amount of tutorials and explanations around. Closures are the equivalent to blocks in swift. google.com.au/… Commented Nov 5, 2015 at 5:27
  • how should i do using closures, i search lots of about but not getting properly Commented Nov 5, 2015 at 5:29

1 Answer 1

4

You can use closure in Swift, Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C.

Closure expression syntax has the following general form:

{ (parameters) -> return type in
    statements
}

Example :

If you need to define any closure as object in class like as below,

class AHServiceCallWrapper {
  var completionBlock: ((AnyObject, NSError) -> Void)? = nil

  func doSomeStuff() {
    var json = [AnyObject]()
    var error : NSError? = nil
    //Do some stuff if completed
     if let completionBlock = self.completionBlock {
            completionBlock(json, error);
     }
  }
}

Now, you can use the implementation like

let serviceCall = AHServiceCallWrapper()
serviceCall.completionBlock =  { (response, error) -> Void in
        //Do the stuff on completion 
    }
serviceCall.doSomeStuff()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.