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))
it shows the error
Ambiguous use of 'init'
what is wrong with it in Swift 3? How to fix it?
UnsafePointer
has initializer for both UnsafePointer
and UnsafeMutablePointer
, and sizeof was moved to MemoryLayout
disambiguate it as:
let valueData = withUnsafePointer(to: &intVal){
return Data(bytes: $0, count: MemoryLayout<NSInteger>.size)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With