Swift 3 and Xcode8 - Ambiguous use of init

2019-03-19 16:31发布

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?

2条回答
虎瘦雄心在
2楼-- · 2019-03-19 16:54

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)
}
查看更多
仙女界的扛把子
3楼-- · 2019-03-19 17:06

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.

查看更多
登录 后发表回答