Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))

it shows the error

Ambiguous use of 'init'

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

like image 687
theDC Avatar asked Sep 19 '16 17:09

theDC


2 Answers

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)
}
like image 183
Jans Avatar answered Nov 02 '22 17:11

Jans


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.

like image 36
Martin R Avatar answered Nov 02 '22 16:11

Martin R