菜鸟教程小白 发表于 2022-12-11 18:39:49

ios - 无法为类型 Unsafepointer Swift 3.0 转换初始化变量


                                            <p><p>您好,我正在将现有的 swift 2.0 代码转换为 swift 3.0,但在转换时遇到错误:</p>

<blockquote>
<p>Cannot invoke initializer for type &#39;UnsafePointer&#39; with an argument list of type &#39;(UnsafeRawPointer)&#39;</p>
</blockquote>

<p>这是我的代码:</p>

<pre><code>extension Data {

var hexString : String {
    let buf = UnsafePointer&lt;UInt8&gt;(bytes) // here is the error
    let charA = UInt8(UnicodeScalar(&#34;a&#34;).value)
    let char0 = UInt8(UnicodeScalar(&#34;0&#34;).value)

    func itoh(_ i: UInt8) -&gt; UInt8 {
      return (i &gt; 9) ? (charA + i - 10) : (char0 + i)
    }

    let p = UnsafeMutablePointer&lt;UInt8&gt;.allocate(capacity: count * 2)

    for i in 0..&lt;count {
      p = itoh((buf &gt;&gt; 4) &amp; 0xF)
      p = itoh(buf &amp; 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&lt;UInt8&gt;) in
    for i in 0..&lt;count {
      p = itoh((buf &gt;&gt; 4) &amp; 0xF)
      p = itoh(buf &amp; 0xF)
    }
}
</code></pre>

<p>或者,使用 <code>Data</code> 是字节集合的事实:</p>

<pre><code>for (i, byte) in self.enumerated() {
    p = itoh((byte &gt;&gt; 4) &amp; 0xF)
    p = itoh(byte &amp; 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]
查看完整版本: ios - 无法为类型 Unsafepointer Swift 3.0 转换初始化变量