COMMUNICATION BETWEEN OBJECTS IN OBJECTIVE C AND SWIFT COMPARED WITH ACTIONSCRIPT – PART 4

Blocks/Closures

Blocks are another way that Objective C performs callbacks. Flash and Swift uses this technique as well, where they are called closures. Basically this involves passing in a function/method/message to the child, whilst maintaining the focus of the parent. So it would be a method that the child can call, and local variables within the closure are based on local variables where the closure is defined. I find it makes your code hard to read, (especially in Objective C where the syntax can be a struggle to get right too!) but it’s still a valid technique.
One caveat – ‘this’ in an ActionScript closure is actually assumed to be in the global scope.

ActionScript3:

Parent.as (Document class)
[sourcecode language=”actionscript3″]
package {
import flash.display.MovieClip;

public class Parent extends MovieClip {
private var string:String;
public function Parent() {
string="I am Parent";
// function closure
var parentMethod:Function=function():String {
return(string);
}

var child:Child=new Child();
child.runThis(parentMethod);
}

}

}
[/sourcecode]
Child.as
[sourcecode language=”actionscript3″]
package {
public class Child {
private var string:String;
public function Child() {
string="I am Child";
}
public function runThis(functionToRun:Function):void {
functionToRun();
}
}

}
//traces I am Parent
[/sourcecode]

Objective C:

In Parent.m
[sourcecode language=”objc”]
NSString *string = @"I am Parent";
NSString * (^parentMethod)() =
^ NSString * () {
return string;
};
Child *child = [[Child alloc] init];
NSLog(@"%@", [child runThis:parentMethod]);
[/sourcecode]
In Child.m
[sourcecode language=”objc”]
-(NSString *)runThis:(NSString *(^)())blockToRun {
NSString *string = @"I am Child";
return(blockToRun());
}
//NSLogs I am Parent
[/sourcecode]

Swift:

The following works well in playgrounds:
[sourcecode language=”objc”]
import Cocoa
var parent:Parent=Parent()
parent.go() //Note that this outputs I am Parent
class Parent {
var string="I am Parent"
var child = Child()
func parentMethod()->NSString {
return string
}
func go()->NSString {
return child.runThis(parentMethod)
}
}
class Child {
var string="I am Child"
func runThis(closure: () -> NSString)->NSString {
return closure()
}
}
[/sourcecode]

Unknown's avatar

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with: ,
Posted in Flash, Objective C, Swift
One comment on “COMMUNICATION BETWEEN OBJECTS IN OBJECTIVE C AND SWIFT COMPARED WITH ACTIONSCRIPT – PART 4

Leave a Reply

Discover more from Before I forget...

Subscribe now to keep reading and get access to the full archive.

Continue reading