ios – Swift指针算术和解除引用;将一些类似C的地图代码转换为Swift

前端之家收集整理的这篇文章主要介绍了ios – Swift指针算术和解除引用;将一些类似C的地图代码转换为Swift前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一点似乎没有工作的 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的方式,当我非常清楚语法时.

我希望错误在swift代码中 – 因为这一切都在目标C版本中工作.哪里出错?

@H_404_13@解决方法
您正在指定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
原文链接:https://www.f2er.com/iOS/331957.html

猜你在找的iOS相关文章