Search code examples
swiftnsmutabledata

How to pass to NSMutableData.appendBytes an array index position different from zero


I've an [UInt8] array containing ASCII codes and I want to create a String from it passing from a NSMutableData

I use the method appendBytes and pass to it the swift array address and everything works fine

The problem is when I need to pass a different from zero index, the expression &arr[5] is obviously wrong

The example below shows how to create the string starting from zero and taking 5 characters (the string "hello").

How do I must modify the code to start from position 6 and get the string "world"?

    var arr = [UInt8](count:100, repeatedValue:0)
    arr[0] = 104 // h
    arr[1] = 101 // e
    arr[2] = 108 // l
    arr[3] = 108 // l
    arr[4] = 111 // o
    arr[5] = 32 // space
    arr[6] = 119 // w
    arr[7] = 111 // o
    arr[8] = 114 // r
    arr[9] = 108 // l
    arr[10] = 100 // d
    var data = NSMutableData()
    data.appendBytes(&arr, length: 5)
    let str = NSString(data: data, encoding: NSASCIIStringEncoding)
    println("string from index zero = \(str)")

Solution

  • You can wrap byte array into NSData and access required bytes using subdataWithRange(...), here is the code:

    let readOnlyData = NSData(bytesNoCopy: &arr, length: arr.count) // notice bytesNoCopy, working with the same bytes
    let subRangeData = readOnlyData.subdataWithRange(NSMakeRange(6, 5))
    let str = NSString(data: subRangeData, encoding: NSASCIIStringEncoding)