Things learned from Objective-C – Cocos2D porting and testing in Swift – Part 2

More things learned from playing around with Swift, Objective-C and Cocos2D

Interoperability between Objective-C and Swift – Initialize patterns

If you have in you Objective-C code an Initialize Pattern to access it in Swift you just use the class name and access the initialize pattern as you would access a static function. Just remember to downcast with the ‘as’ operator returning the class from which you are using the initialization pattern.  The green code below:

var moveToLeftEdge : CCActionMoveTo = CCActionMoveTo(duration: CCTime(birdTime), position: screenLeft);
var turnaround : CCActionFlipX = CCActionFlipX(flipX: true);
var moveBackOffScreen : CCActionMoveTo = CCActionMoveTo(duration: CCTime(birdTime), position: birdStart);
var birdActions = Array<CCAction>();
birdActions.append(moveToLeftEdge);
birdActions.append(turnaround);
birdActions.append(moveBackOffScreen);
birdActions.append(turnaround);

var moveLeftThenBack : CCActionSequence = CCActionSequence.actionWithArray(birdActions) as CCActionSequence;

 

Interoperability between Objective-C and Swift – Objective-C Selectors

To access Objective-C selectors in Swift you define a constant value with the value being the function name to call within your class. See green code below:

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-XID_38

let mySelectorTurnAround: Selector = “turnAround”;
var turnArround : CCActionCallFunc = CCActionCallFunc.actionWithTarget(bird, selector: mySelectorTurnAround) as CCActionCallFunc;

 

Objective-C Struct definition usage and initialization

If you are get the following error message when using struct definitions in Objective-C then the solution is to initialize the struct before usage. Below is an example of than in the green color.

Error Message: Struct ‘struct name’ must be completely initialized before a member is stored to

Original Objective-C Struct definition:

// Bezier configuration structure.
typedef struct _ccBezierConfig {
// End position of the bezier.
CGPoint endPosition;
// Bezier control point 1.
CGPoint controlPoint_1;
// Bezier control point 2.
CGPoint controlPoint_2;
} ccBezierConfig;

In Swift Code Usage

var curve : ccBezierConfig = ccBezierConfig(endPosition: CGPointMake(0, 0), controlPoint_1: CGPointMake(0, 0), controlPoint_2: CGPointMake(0, 0));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s