19

I have tried to run the below code in swift 3

 var values = [UInt8](count:data!.length, repeatedValue:0)
 data!.getBytes(&values, length:data!.length)

where data is 'Data' datatype (NSData is change to 'Data' as per swift 3 guidelines)

I am not able to run the above code in Swift 3. Compiler gives error that "Argument Repeated value must precede argument". The same line of code was working in Swift 2.2

What will be the solution ?

Rince Thomas
  • 4,158
  • 5
  • 25
  • 44
iDev
  • 531
  • 1
  • 5
  • 15
  • Although question differs slightly answer should be same: http://stackoverflow.com/questions/38090320/writing-data-to-an-nsoutputstream-in-swift-3 – Desdenova Jun 29 '16 at 11:09

2 Answers2

43

For Swift3 just use following:

let array = [UInt8](yourDataObject)

That's all, folks!)

sVd
  • 1,043
  • 12
  • 12
  • How do you use this? I'm trying to convert the following from Objective-C: int16_t value = 0; CGFloat result = NAN; if (tempCharacteristic) { [[tempCharacteristic value] getBytes:&value length:sizeof (value)]; result = (CGFloat)value / 10.0f; } // tempCharacteristic is a CBCharacteristic – Surz Jul 19 '17 at 23:26
  • I'm afraid but to acheeve desired result you need to make several steps. Unfortunately I have't much experience with CB but as I see you need Int16 value and than divide it to get Float. From my point of view you can reach this by following: let bytes = [UInt8](tempCharacteristic.value); let pointer = UnsafePointer(bytes); let fPointer = pointer.withMemoryRebound(to: Int16.self, capacity: 2) { return $0 }; let value = Int16(fPointer.pointee); Hope this helps. (Of course remove all semicolons ;) ) – sVd Jul 20 '17 at 10:48
  • Thanks so much for your pointer, @sVd. I am still having trouble converting the snippet - would you mind checking out my question? https://stackoverflow.com/questions/45287488/trouble-converting-nsdata-objective-c-code-to-swift – Surz Jul 24 '17 at 18:22
  • I see, @Surz, you found the correct answer. Sorry I wrote my snippet just from my head without compiler. Cheerss! ) – sVd Jul 28 '17 at 14:47
25

It means that the arguments order has been reversed in Swift 3.

For NSData:

var values = [UInt8](repeating:0, count:data!.length)
data.getBytes(&values, length: data!.length)

For Data:

var values = [UInt8](repeating:0, count:data!.count)
data.copyBytes(to: &values, count: data!.count)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • 2
    This was for an early version of Swift 3. For the current Swift 3 and for Swift 4 you should use @svd's answer. – Eric Aya Jun 08 '17 at 17:36