ios - 无法为类型 Unsafepointer Swift 3.0 转换初始化变量
<p><p>您好,我正在将现有的 swift 2.0 代码转换为 swift 3.0,但在转换时遇到错误:</p>
<blockquote>
<p>Cannot invoke initializer for type 'UnsafePointer' with an argument list of type '(UnsafeRawPointer)'</p>
</blockquote>
<p>这是我的代码:</p>
<pre><code>extension Data {
var hexString : String {
let buf = UnsafePointer<UInt8>(bytes) // here is the error
let charA = UInt8(UnicodeScalar("a").value)
let char0 = UInt8(UnicodeScalar("0").value)
func itoh(_ i: UInt8) -> UInt8 {
return (i > 9) ? (charA + i - 10) : (char0 + i)
}
let p = UnsafeMutablePointer<UInt8>.allocate(capacity: count * 2)
for i in 0..<count {
p = itoh((buf >> 4) & 0xF)
p = itoh(buf & 0xF)
}
return NSString(bytesNoCopy: p, length: count*2, encoding: String.Encoding.utf8.rawValue, freeWhenDone: true)! as String
}
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>在 Swift 3 中你必须使用 <a href="https://developer.apple.com/documentation/foundation/data/1780450-withunsafebytes" rel="noreferrer noopener nofollow"><code>withUnsafeBytes()</code></a>访问 <code>Data</code> 值的原始字节。在你的情况下:</p>
<pre><code>withUnsafeBytes { (buf: UnsafePointer<UInt8>) in
for i in 0..<count {
p = itoh((buf >> 4) & 0xF)
p = itoh(buf & 0xF)
}
}
</code></pre>
<p>或者,使用 <code>Data</code> 是字节集合的事实:</p>
<pre><code>for (i, byte) in self.enumerated() {
p = itoh((byte >> 4) & 0xF)
p = itoh(byte & 0xF)
}
</code></pre>
<p>请注意,您的代码中还有另一个问题:</p>
<pre><code>NSString(..., freeWhenDone: true)
</code></pre>
<p>使用<code>free()</code>来释放内存,也就是说必须是
用 <code>malloc()</code> 分配。</p>
<p>其他(较短,但可能效率较低)的创建方法
<code>Data</code> 值的十六进制表示可以在以下位置找到
<a href="https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift" rel="noreferrer noopener nofollow">How to convert Data to hex string in swift</a> .</p></p>
<p style="font-size: 20px;">关于ios - 无法为类型 Unsafepointer Swift 3.0 转换初始化变量,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/46169483/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/46169483/
</a>
</p>
页:
[1]