7

I have this little bit of Swift code that does not seem to be working...

// earlier, in Obj C...
    typedef struct _Room {
        uint8_t *map;
        int width;
        int height;
    } Room;

A Room is part of a stab at a roguelike game if you're curious. I'm trying to rewrite a couple of parts in Swift. Here's the code that appears broken, and what I hope I am doing as comments:

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

Something is wrong here because simple tests show the value of pointValue is not what I know I am looking at on the map, having set a very simple location (1, 1) to a known value. It seems pretty obvious that Swift is not supposed to be doing this kind of thing but it's a conversion with the aim of learning the Way of Swift when I know the syntax well enough.

I expect the error is in the swift code - since this was all working in the objective C version. Where's the error?

Adam Eberbach
  • 12,309
  • 6
  • 62
  • 114

1 Answers1

11

You are assigning locationPointer to point to the new location, but still using ptr in the next line, and the value of ptr has not been changed. Change your last line to:

var pointValue = locationPointer.memory

or you could change your pointer to a var and advance it:

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
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • 5
    Why the down vote? Don't down vote without a comment. That isn't helping anyone. – vacawama Sep 14 '14 at 13:20
  • Argh! That's the kind of mistake you get for programming late. Thanks, I will try it and accept later. – Adam Eberbach Sep 14 '14 at 20:33
  • Or, you can use ```MemoryLayout<_Room>.size``` instead ```(Int(room.width) * Int(point.y)) + Int(point.x)``` – isnullxbh Aug 22 '18 at 06:48
  • @isnullxbh, I don't think the size of the `_Room` `struct` matters. This calculation needs to vary depending on the values of `room.width` and the specific `point.x` and `point.y` that is being accessed. – vacawama Aug 22 '18 at 11:34
  • @vacawama, yes, of course, you're right. Excuse me :) – isnullxbh Aug 22 '18 at 11:39