Swift 3 and Xcode8 - Ambiguous use of init

别来无恙 提交于 2019-12-20 20:26:11

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/39579121/swift-3-and-xcode8-ambiguous-use-of-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!