Skip to content
Axel Roest edited this page Oct 28, 2020 · 1 revision

Normally in swift there’s this magic feature that a closure has, an extra power compared to normal functions. It can refer to local variables in the scope where it’s defined, or to member variables if it’s defined somewhere in an instance method.

In order to do that, swift quietly creates a little block of memory that either contains a copy of the variables you’re closing over or a pointer to them or something similar. It then adds a function pointer to the block, puts the block on the heap as a reference counted object and passes a reference to that object into whatever place is accepting the closure, a local variables, parameter of a function, instance variable, etc.

The life of that memory block is controlled by arc and lives until all strong references are released.

Meanwhile the closure can be executed and when that’s done the code in the function will gain access to the copies/references in the little memory block.

So all this magic just exists so you can refer to variables outside the closure and swift handles it for you.

Swift for arduino doesn’t have any of that runtime. So to prevent linker errors, I always define callbacks with convention c. That disables the closure system and makes a simple c style function pointer instead.

The effect of this is you’re not allowed to refer to variables outside the block unless they’re global.

As swift programmers we get so used to all the above we take it for granted. But it has mechanisms and costs under the hood. The biggest for S4A is it needs arc to control the life of the memory block. 22:11 So you can have closures on instance variables but they can’t refer to any instance members or self. Making them a bit useless for most normal uses. :) 22:11 It would be fair to say normal closures are not yet supported in S4A. 22:13 I’m contemplating making a single threaded non re-entrant version of ARC to fix many of the shortcomings like this. Currently threads are the main barrier to ARC. The runtime ARC has to be strictly thread safe, meaning pthreads dependencies.