3

I'm following a tutorial written in objective-c here and I've converted most things to swift already, however some lines just won't work.

for example, I've converted the following structs:

typedef struct { MessageType messageType; } Message; typedef struct { Message message; } MessageMove; 

to this:

struct Message { var messageType:MessageType } struct MessageMove { var message:Message } 

and in another line, the tutorial does the following:

- (void)match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID { Message *message = (Message*)[data bytes]; if (message->messageType == kMessageTypeMove) { MessageMove *messageMove = (MessageMove*) [data bytes]; } } 

I've tried changing this to the following:

func matchDidReceiveDataFromPlayer(match: GKMatch, data: NSData, player: GKPlayer) { //1 var message = data.bytes as Message //DOESNT WORK if (message.messageType == MessageType.kMessageTypeGameBegin) //2 var messageMove = data.bytes as MessageMove //WORKS } 

but the first cast (//1) doesn't work, it says the following:

UnsafePointer<Void> not convertible to Message

however the second cast (//2) works. Is it because I'm doing a check on the message type in the if statement?

any ideas on how to fix this?

0

1 Answer 1

2

Is it because I'm doing a check on the message type in the if statement?

No. It's because, thanks to the first error on //1, the compiler never reaches the second line //2 at all. You'd get the same error there, if the compiler ever reached it.

Now let's talk about the syntax. If you truly believe that data.bytes is the same as a Message instance, you would say:

let message = UnsafePointer<Message>(data.bytes).memory 

However, I personally would rather tend to doubt that the data you get from Objective-C would constitute a Swift struct! What went in at the Objective-C end, after all, is presumably a C struct, which is a different animal.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation. but what do you mean by what went in at the objective-c end? even if my sendData() method sends a Swift struct? or are you saying that under the hood the objective-c api is called when dealing with NSData?
I've never used Game Kit. I know nothing of how this method will be called or how the bytes will get into that NSData. I answered based on what you've said.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.