So today I went back to coding after a while (half a year? plus before it wasn't like I was any good lol ...) and wanted to pickup Swift but this stopped me just before I even gave it a good try:
BTW I'm trying to make a "myWorld" variable that would act as the scene handler later on, well, u get the idea......
http://postimg.org/image/4n1izokcj/
(the error can't be seen here on stackoverflow, little resolution upload...)
the old Obj-C way that worked for me for initialising a new SKNode:
#interface Level() {
SKNode* myWorld;
}
#implementation Level
-void setUpScene {
myWorld = [SKNode node]
[self addChild:myWorld]
}
the new Swift way that I thought should work:
var myWorld:SKNode?
class Level:SKScene {
func setUpScene() {
myWorld = SKNode.node()
self.addChild(myWorld!)
}
}
what am I doing wrong? (the "myWorld! = SKNode.node()" does the same...)
pls no flame.
thx for any constructive reply ^__^
OK, I'm just blind... the syntax is
myWorld = SKNode()
& not
myWorld = SKNode.node()
jeez... feel free to erase this question editors...
Related
I'm new to Swift and Sphero development but I've been asked to do a game based on collisions with the Sphero.
I've managed to implement the driving part without problems so far, but I'm having problems with collisions.
I've been looking for code examples and similar issues all over the Internet but everything I've found is based in other languages like JAVA or ObjectiveC.
The code provided by Sphero's official page is the following:
**Enable collision detection**
robot.enableCollisions(true)
robot.sendCommand(RKConfigureCollisionDetectionCommand(forMethod: .Method3, xThreshold: 50, xSpeedThreshold: 30, yThreshold: 200, ySpeedThreshold: 0, postTimeDeadZone: 0.2))
**Handle Async Messages on collision**
func handleAsyncMessage(message: RKAsyncMessage!, forRobot robot: RKRobotBase!) {
if let collisionMessage = message as? RKCollisionDetectedAsyncData {
// handleCollisionDetected
}
}
I've tried this in many ways, but when executed it won't send any command or even access the handleAsyncMessage method, so I'm starting to think this code is not implemented for Swift.
These doubts were intensified when I found that the collision streaming method was implemented somewhere in the official page for ObjectiveC, but for Swift I could only find //Coming Soon!.
Collisions
[_robot sendCommand:[[RKConfigureCollisionDetectionCommand alloc]
initForMethod:RKCollisionDetectionMethod3
xThreshold:50 xSpeedThreshold:30 yThreshold:200 ySpeedThreshold:0 postTimeDeadZone:.2]];
...
- (void)handleAsyncMessage:(RKAsyncMessage *)message forRobot:(id<RKRobotBase>)robot {
if( [message isKindOfClass:[RKCollisionDetectedAsyncData class]]) {
RKCollisionDetectedAsyncData *collisionAsyncData = (RKCollisionDetectedAsyncData *) message;
float impactAccelX = [collisionAsyncData impactAcceleration].x;
float impactAccelY = [collisionAsyncData impactAcceleration].y;
float impactAccelZ = [collisionAsyncData impactAcceleration].z;
float impactAxisX = [collisionAsyncData impactAxis].x;
float impactAxisY = [collisionAsyncData impactAxis].y;
float impactPowerX = [collisionAsyncData impactPower].x;
float impactPowerY = [collisionAsyncData impactPower].y;
float impactSpeed = [collisionAsyncData impactSpeed];
}
}
Should I change the language to ObjectiveC or do you guys know any way to implement this using Swift?
Thank you in advance.
This SDK is written in Objective-C; Swift works through Objective-C interoperability built into Swift. Everything should work regardless of the language you choose. It looks like you might be missing the response observer. On the robot you call robot.addResponseObserver(self) making sure you implement the RKResponseObserver protocol.
I am porting some AppDelegate code for a plugin Objective-C to Swift.
My Objective-C is pretty good but I am stumped at understanding whats going on here. This is the code I am stuck on porting:
void (^safeHandler)(UIBackgroundFetchResult) = ^(UIBackgroundFetchResult result){
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(result);
});
};
I understand that the the ^ is for code blocks, but looking at this as a whole I am lost as to what is going on and how to port this to Swift.
I don't understand how there are two bracketed portions here:
void (^safeHandler)(UIBackgroundFetchResult)
If you can advise what that syntax is and how to port to Swift I would greatly appreciate it!
It's a block, which is a closure in Swift. This block is named safeHandler and takes a UIBackgroundFetchResult parameter and returns void.
This is the equivalent type:
let safeHandler: (UIBackgroundFetchResult) -> ()
And the whole thing would be
let safeHandler: (UIBackgroundFetchResult) -> () = { result in
dispatch_async(dispatch_get_main_queue()) {
completionHandler(result)
}
}
Note: block syntax is notoriously wonky. You can use this site to see the various block syntax forms: http://goshdarnblocksyntax.com/
I'm trying to use the PRTween library in a Swift iPhone app.
Original example code from GitHub:
PRTweenPeriod *period = [PRTweenPeriod periodWithStartValue:100 endValue:200 duration:3];
PRTweenOperation *operation = [[PRTweenOperation new] autorelease];
operation.period = period;
operation.target = self;
operation.timingFunction = &PRTweenTimingFunctionLinear;
My Swift port:
var period = PRTweenPeriod.periodWithStartValue(100, endValue: 200, duration: 3) as PRTweenPeriod
var operation = PRTweenOperation()
operation.period = period
operation.target = self
operation.timingFunction = PRTweenTimingFunctionLinear
Xcode is giving me this error:
'PRTweenOperation' does not have a member named 'timingFunction'
I'm not sure how to fix this. I can clearly see the member definition in PRTween.h. I'm thinking it might be related to the fact that this is where the definition of PRTweenTimingFunction takes me.
typedef CGFloat(*PRTweenTimingFunction)(CGFloat, CGFloat, CGFloat, CGFloat);
Has anyone else seen an error like this? Any suggestions for fixes?
P.S. I'm not really sure what to call that typedef. Is it a function pointer?
EDIT
As a workaround, I used this code that does not ask for a timing function:
let period = PRTweenPeriod.periodWithStartValue(100, endValue: 200, duration: 2) as PRTweenPeriod
PRTween.sharedInstance().addTweenPeriod(period,
updateBlock: { (p: PRTweenPeriod!) in
NSLog("\(Int(p.tweenedValue))"
},
completionBlock: { NSLog("Completed tween") })
Yes, that's a function pointer. This is a current limitation of C interoperability:
Note that C function pointers are not imported in Swift.
You might consider filing a bug if you'd like this to work. (Note that block-based APIs are fine and work with Swift closures.)
I am trying to make my code run, but it always stops.
Can someone of you help me solve the problem.
For some reason it wont accept this.
-(Animal *) getAnimalAt:(int)input {
//NSLog(#"show input %ld", input);
Animal *ani = [animals objectAtIndex:input];
return ani;
}
I call this method in my main by :
for(int i=0;i< count;i++){
Animal *ani = [farm getAnimalAt:i];
NSLog(#"ani : %#",[ani makeSound]);
NSLog(#"ani : %#",[ani doFly]);
}
If you need any more info or code please ask.
Also do any of you have found a good tutorial? I cant seem to find one?
Or a site like codingbat would be very helpfull.
If animals is just an NSArray you could remove the getAnimalAt: method and just use the NSArray. Then you could do something like:
for (Animal *ani in animals) {
NSLog(#"ani : %#", [ani makeSound]);
NSLog(#"ani : %#", [ani doFly]);
}
which will prevent any problems with count being greater than the number of elements in animals
I'm putting together a Mac OS X Application and I'm trying to register to receive Display Reconfiguration notices, but I'm very lost right now. I've been reading Apple's documentation and some forums posts, etc., but everything seems to assume a better knowledge of things than I apparently possess. I understand that I have to request the callback inside a run loop for it to work properly. I don't know how to set up a basic run loop for it, though. I also feel like the example Apple has in their documentation is missing stuff they are expecting me to already know. To display my ignorance here is what I feel like things should look like.
NSRunLoop *rLoop = [NSRunLoop currentRunLoop];
codeToStartRunLoop
void MyDisplayReconfigurationCallBack (
CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *userInfo);
{
if (flags & kCGDisplayAddFlag) {
NSLog (#"Display Added");
}
else if (kCGDisplayRemoveFlag) {
NSLog (#"Display Removed");
}
}
CGDisplayRegisterReconfigurationCallback(MyDisplayReconfigurationCallBack, NULL);
The actual code I got was from Apple's Example, but it tells me that flags is an undeclared identifier at this point and won't compile. Not that it would work right since I don't have it in a run loop. I was hoping to find a tutorial somewhere that explains registering for system callback in a run loop but have not been successful. If anyone could point me in the right direction I'd super appreciate it.
(I'm sure that you'll be able to tell from my question that I'm very green. I taught myself Objective-C out of a book as my first programming language. I skipped C, so every once in a while I hit a snag somewhere that I can't figure out.)
If you're writing a Mac OS X application, the AppKit has already set up a run loop for you, so you don't need to worry about that part. You really only need to create your own run loop in Cocoa when you are also creating your own thread.
For the "undeclared identifier" part, it looks like it's due to a typo/syntax mistake:
void MyDisplayReconfigurationCallBack (CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *userInfo);
// Semicolon makes this an invalid function definition^^
{
// This is an anonymous block,* and flags wasn't declared in it
if (flags & kCGDisplayAddFlag) {
// etc.
}
Also, unlike some other languages, you can't declare or define functions inside of other functions, methods, or blocks* -- they have to be at the top level of the file. You can't put this in the same place where you call CGDisplayRegisterReconfigurationCallback.
Just as an sample (I have no idea what the rest of your code really looks like):
// MyClassThatIsInterestedInDisplayConfiguration.m
#import "MyClassThatIsInterestedInDisplayConfiguration.h"
// Define callback function at top level of file
void MyDisplayReconfigurationCallBack (
CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *userInfo)
{
if (flags & kCGDisplayAddFlag) {
NSLog (#"Display Added");
}
else if (kCGDisplayRemoveFlag) {
NSLog (#"Display Removed");
}
}
#implementation MyClassThatIsInterestedInDisplayConfiguration
- (void) comeOnBabyAndDoTheRegistrationWithMe {
// Register callback function inside a method
CGDisplayRegisterReconfigurationCallback(MyDisplayReconfigurationCallBack,
NULL);
}
#end
*The basic C curly-brace-delimited thing, not the new cool Obj-C ad hoc function thing.