xcode Swift 3 和 Xcode8 - init 的模糊使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39579121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:17:06  来源:igfitidea点击:

Swift 3 and Xcode8 - Ambiguous use of init

iosswiftxcodeswift3xcode8

提问by theDC

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

在我安装 Xcode 8 并将项目转换为 Swift 3 之前,以下行很好。现在转换后它看起来像这样:

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

it shows the error

它显示错误

Ambiguous use of 'init'

'init' 的歧义使用

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

Swift 3 有什么问题?如何解决?

采纳答案by Martin R

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

Data从简单值创建的最简单方法是通过 via UnsafeBufferPointer,然后您不需要任何显式指针转换或大小计算:

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 Dataand back, see for example round trip Swift number types to/from Data.

有关从值到Data和返回的更通用的转换方法,请参阅例如往返 Swift 数字类型到/从 Data

回答by Jans

UnsafePointerhas initializer for both UnsafePointerand UnsafeMutablePointer, and sizeof was moved to MemoryLayoutdisambiguate it as:

UnsafePointer有初始值都为UnsafePointerUnsafeMutablePointer,和sizeof被转移到MemoryLayout歧义它:

let valueData = withUnsafePointer(to: &intVal){
    return Data(bytes: ##代码##, count: MemoryLayout<NSInteger>.size)
}