【问题标题】:Issue updating code to Swift 5.1 'withUnsafeBytes is deprecated: use withUnsafeBytes(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R instead'将代码更新到 Swift 5.1 'withUnsafeBytes 已弃用:使用 withUnsafeBytes(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R instead'
【发布时间】:2020-07-06 16:54:58
【问题描述】:

我正在使用一个简单的扩展来打包和解包数据,下面的代码目前仍然有效,但它向我发出了警告,我想更新它以防止出现问题。

对此有两个类似的问题,但我无法成功应用那里讨论的内容。所以我希望有人能给我一些见解。

发出警告的扩展程序:

extension Data {
    var unsafeBytes : UnsafePointer<UInt8> {
        return self.withUnsafeBytes { return $0 } //'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
    }
}

使用它的功能之一:

func upack(_ bin: Data) -> Data {
        let unsafeBin = bin.unsafeBytes
        let output = UnsafeMutablePointer<UInt8>.allocate(capacity: 540)
        
        if (!nfc_upack(key, unsafeBin, output)) {
            log.warning("Unpacking failed")
        }
        
        return Data(bytes: output, count: 540)
    }

编辑:nfc_upack 导致 https://github.com/socram8888/amiitool/blob/master/amiibo.c#L73

就像我说的,目前它工作正常,但我想在它成为问题之前解决这个问题。

【问题讨论】:

  • 能分享一下nfc_upack的api,参数是什么。
  • @AnkitThakur 它引用了这个 GitHub 文件中的第 73 行(唯一的区别是名称):github.com/socram8888/amiitool/blob/master/amiibo.c#L73 该函数是包含 var key : UnsafeMutablePointer&lt;nfc3d_amiibo_keys&gt; = UnsafeMutablePointer&lt;nfc3d_amiibo_keys&gt;.allocate(capacity: 1) 的结构的一部分

标签: swift deprecated swift5 unsafe-pointers


【解决方案1】:

所以要解决这个警告,实际的实现方式是这样的:

let data = Data()
var output = Data(count: 540)

var satus:Bool = false
satus = output.withUnsafeMutableBytes { outputBytes in
    data.withUnsafeBytes { dataBytes in
        nfc_upack(key, unsafeBin, output)
    }
}

statusnfc_upack api 共享的输出布尔值。 然后您可以检查状态是否为真,然后输出参数将具有有效值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多