Ada*_*ach 7 pointers dereference ios swift
我有一点似乎没有工作的Swift代码......
// earlier, in Obj C...
typedef struct _Room {
uint8_t *map;
int width;
int height;
} Room;
Run Code Online (Sandbox Code Playgroud)
如果你很好奇,房间就是刺激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
Run Code Online (Sandbox Code Playgroud)
这里出了点问题,因为简单的测试显示pointValue的值不是我所知道的我在地图上看到的,已经将一个非常简单的位置(1,1)设置为已知值.似乎很明显,Swift不应该做这种事情,但它是一个转换,目的是学习Swift的方式,当我非常清楚语法时.
我希望错误是在快速代码中 - 因为这一切都在目标C版本中工作.哪里出错?
vac*_*ama 11
您指定locationPointer
指向新位置,但仍在ptr
下一行中使用,并且值ptr
尚未更改.将您的最后一行更改为:
var pointValue = locationPointer.memory
Run Code Online (Sandbox Code Playgroud)
或者您可以将指针更改为a 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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2509 次 |
最近记录: |