Swift array element address

This is a practical question, I am sending a file breaking it into chests, say 1000 bytes

data = NSData.dataWithContentsOfFile(path)
var dataPackage : [Byte](count: 1000, repeatedValue: 0)

for offset = 0; offset < data.length; {
     // omit some range check here
     data.getBytes(&dataPackage, NSRange(location: offset, length: 1000))
     send(dataPackage)
}

Everything was wonderful until I wanted to insert the serial number in the dataPackage, to position 0, so, naturally, I would change the above to

data.getBytes(&dataPackage[1], NSRange(location: offset, length: 999))

It turned out that only one single item is copied to dataPackage. The remaining 999 items were copied to d-know-where

My question is: 1) how to do this, and 2) how the array is solved in swift, so that the data & data [i] = & data + i (as shown in the first example) but & data [i + k]! = & data [i] + k

Edit: I solved (1) by doing

data.getBytes(&dataPackage + 1, NSRange(location: offset, length: 999))

Question (2) remains

+4
source share
1 answer

getBytes(&dataPackage[i] + k, ..), , " "

:

struct MyStruct {
    var _val = [Int](count: 1000, repeatedValue: 0);
    subscript(idx:Int) -> Int {
        get {
            println("get: [\(idx)] -> val(\(_val[idx]))")
            return _val[idx]
        }
        set(val) {
            println("set: [\(idx)] old(\(_val[idx])) -> new(\(val))")
            _val[idx] = val
        }
    }
}

func myFunc(ptr:UnsafeMutablePointer<Int>, val:Int) {
    println("mutating: ptr(\(ptr)) <- \(val)")
    ptr.memory = val
}

MyStruct - Array.

myFunc .

, yo do:

var foo = MyStruct()
myFunc(&foo[1], 12)

:

get: [1] -> val(0)
mutating: ptr(0x00007fff561619d8) <- 12
set: [1] old(0) -> new(12)

?

  • somewhere
  • Mutate somewhere
  • somewhere

, somewhere.

:

var foo = MyStruct()
myFunc(&foo[1] + 1, 12)

:

get: [1] -> val(0)
set: [1] old(0) -> new(0)
mutating: ptr(0x00007fff5c0b79e0) <- 12

, , :

  • somewhere
  • let corrupted somewhere + 1
  • Write-back unmutated somewhere
  • somewhere
  • Mutate corrupted

, :

var foo = [Int](count:1000, repeatedValue:0)
myFunc(&foo + 1, 12)

:

  • let ptr foo
  • let ptr ptr + 1
  • Mutate ptr

foo[1] 12 , .

in-out (&) of Array , .

UnsafeMutablePointer, :

  • nil,
  • UnsafeMutablePointer
  • in-out, l , lvalue
  • in-out [Type],

Array .

, ¬AnArrayLvalue ( &array[i]) UnsafeMutablePointer<Type> , 1, + - it.

+3

All Articles