[英]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. 我下面的教程写在Objective-C 在这里 ,我已经转换最事情迅速,但有些线路是不会工作。
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: 但第一个演员(// 1)不起作用,它说如下:
UnsafePointer<Void> not convertible to Message
however the second cast (//2) works. 然而第二个演员(// 2)有效。 Is it because I'm doing a check on the message type in the if statement? 是因为我正在检查if语句中的消息类型吗?
any ideas on how to fix this? 有想法该怎么解决这个吗?
Is it because I'm doing a check on the message type in the if statement? 是因为我正在检查if语句中的消息类型吗?
No. It's because, thanks to the first error on //1
, the compiler never reaches the second line //2
at all. 不,这是因为,由于//1
上的第一个错误,编译器永远不会到达第二行//2
。 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: 如果您确实认为data.bytes
与Message实例相同,您会说:
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! 但是,我个人更倾向于怀疑从Objective-C获得的数据是否构成Swift结构! What went in at the Objective-C end, after all, is presumably a C struct , which is a different animal. 毕竟,Objective-C端的内容可能是C结构 ,它是一种不同的动物。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.