DCDC DCDC - 2 months ago 133
Swift Question

Swift 3 and Xcode8 - Ambiguous use of init

Before I installed Xcode 8 and converted project to Swift 3, the following line was fine. Now after conversion it looks like this:

let valueData:Data = Data(bytes: UnsafePointer<UInt8>(&intVal), count: sizeof(NSInteger))


Now it shows error


Ambiguous use of 'init'


what is wrong with it in Swift 3? How to fix it?

Answer

The easiest way to create Data from a simple value is to go via UnsafeBufferPointer, then you don't need any explicit pointer conversion or size calculation:

var intVal = 1000
let data = Data(buffer: UnsafeBufferPointer(start: &intVal, count: 1))
print(data as NSData) // <e8030000 00000000>

For a more generic approach for conversion from values to Data and back, see for example round trip Swift number types to/from Data.