简体   繁体   中英

converting ObjC to Swift - UnsafePointer<Void> not convertible to struct type

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM