Store a closure as a variable in Swift

Jay Dub

In Objective-C, you can define a block's input and output, store one of those blocks that's passed in to a method, then use that block later:

// 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);
            });
     ...
}

So I'm trying to do the equivilant in Swift:

var completionHandler:(Float)->Void={}


init() {
    locationManager = CLLocationManager()
    region = CLBeaconRegion()
    timer = NSTimer()
}

convenience init(region: CLBeaconRegion, handler:((Float)->Void)) {
    self.init()
    locationManager.delegate = self
    self.region = region
    completionHandler = handler
    rangedBeacons = NSMutableArray()
}

The compiler doesn't like that declaration of completionHandler. Not that I blame it, but, how do I define a closure that can be set and used later in Swift?

Martin R

The compiler complains on

var completionHandler: (Float)->Void = {}

because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking a float argument. The following would assign a "do nothing" closure to the completion handler:

var completionHandler: (Float)->Void = {
    (arg: Float) -> Void in
}

and this can be shortened to

var completionHandler: (Float)->Void = { arg in }

due to the automatic type inference.

But what you probably want is that the completion handler is initialized to nil in the same way that an Objective-C instance variable is inititialized to nil. In Swift this can be realized with an optional:

var completionHandler: ((Float)->Void)?

Now the property is automatically initialized to nil ("no value"). In Swift you would use optional binding to check of a the completion handler has a value

if let handler = completionHandler {
    handler(result)
}

or optional chaining:

completionHandler?(result)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Swift variable declaration with closure

From Dev

swift closure stored and access as a variable

From Dev

Swift 2.0 - variable copied in closure?

From Dev

Store Swift Type in variable

From Dev

Closure default initializer missing - swift closure variable declaration?

From Dev

swift variable scope in closure wrt CLGeocoder()

From Dev

How to declare a local variable that is a closure in swift

From Dev

Swift: Closure as a init argument in a class variable

From Dev

get the value of variable out of closure swift

From Dev

swift variable scope in closure wrt CLGeocoder()

From Dev

Swift - return variable from within closure

From Dev

Modify Global Variable Inside Closure (Swift 4)

From Dev

What is the difference between swift variable and function when use closure in variable?

From Dev

converting an Objective-C block variable to a Swift closure variable?

From Dev

How To Store Swift function in a variable

From Dev

How To Store Swift function in a variable

From Dev

When to use equal sign after declare a variable with closure in Swift

From Dev

Swift is unable to type infer variable containing closure that returns Bool

From Dev

How can I get initial closure variable in Swift?

From Dev

Why can't Swift closure variable types be implicitly unwrapped optionals?

From Dev

Cannot change variable from a closure in the same class [swift 3.0]

From Dev

How to store a generic closure?

From Dev

Store a closure with generic type

From Dev

How to store this objectiveC block inside a swift variable?

From Dev

How to store a variable in Swift - login system?

From Dev

How to store a variable in Swift - login system?

From Dev

Store a swift closure as a property on an objective-c class where the block is declared using a typedef

From Dev

Swift: How do I store an array of object by reference from completion handler (closure)?

From Dev

typealias closure error in swift

Related Related

  1. 1

    Swift variable declaration with closure

  2. 2

    swift closure stored and access as a variable

  3. 3

    Swift 2.0 - variable copied in closure?

  4. 4

    Store Swift Type in variable

  5. 5

    Closure default initializer missing - swift closure variable declaration?

  6. 6

    swift variable scope in closure wrt CLGeocoder()

  7. 7

    How to declare a local variable that is a closure in swift

  8. 8

    Swift: Closure as a init argument in a class variable

  9. 9

    get the value of variable out of closure swift

  10. 10

    swift variable scope in closure wrt CLGeocoder()

  11. 11

    Swift - return variable from within closure

  12. 12

    Modify Global Variable Inside Closure (Swift 4)

  13. 13

    What is the difference between swift variable and function when use closure in variable?

  14. 14

    converting an Objective-C block variable to a Swift closure variable?

  15. 15

    How To Store Swift function in a variable

  16. 16

    How To Store Swift function in a variable

  17. 17

    When to use equal sign after declare a variable with closure in Swift

  18. 18

    Swift is unable to type infer variable containing closure that returns Bool

  19. 19

    How can I get initial closure variable in Swift?

  20. 20

    Why can't Swift closure variable types be implicitly unwrapped optionals?

  21. 21

    Cannot change variable from a closure in the same class [swift 3.0]

  22. 22

    How to store a generic closure?

  23. 23

    Store a closure with generic type

  24. 24

    How to store this objectiveC block inside a swift variable?

  25. 25

    How to store a variable in Swift - login system?

  26. 26

    How to store a variable in Swift - login system?

  27. 27

    Store a swift closure as a property on an objective-c class where the block is declared using a typedef

  28. 28

    Swift: How do I store an array of object by reference from completion handler (closure)?

  29. 29

    typealias closure error in swift

HotTag

Archive