我有一点似乎没有工作的
Swift代码……
// earlier,in Obj C... typedef struct _Room { uint8_t *map; int width; int height; } Room;
如果你很好奇,房间就是刺激roguelike游戏的一部分.我正在尝试在Swift中重写几个部分.这是看起来破碎的代码,以及我希望我做的评论:
let ptr = UnsafePointer<UInt8>(room.map) // grab a pointer to the map out of the room struct let offset = (Int(room.width) * Int(point.y)) + Int(point.x) // calculate an int offset to the location I am interested in examining let locationPointer = ptr + offset // pointer advances to point to the offset I want var pointValue = ptr.memory // What I used to get with *ptr
这里出了点问题,因为简单的测试显示pointValue的值不是我所知道的我在地图上看到的,已经将一个非常简单的位置(1,1)设置为已知值.很明显,Swift不应该做这种事情,但它是一个转换,目的是学习Swift的方式,当我非常清楚语法时.
解决方法
您正在指定locationPointer指向新位置,但仍在下一行中使用ptr,并且ptr的值尚未更改.将您的最后一行更改为:
var pointValue = locationPointer.memory
或者你可以改变指向var的指针并推进它:
var ptr = UnsafePointer<UInt8>(room.map) // grab a pointer to the map out of the room struct let offset = (Int(room.width) * Int(point.y)) + Int(point.x) // calculate an int offset to the location I am interested in examining ptr = ptr + offset // pointer advances to point to the offset I want var pointValue = ptr.memory // What I used to get with *ptr