【问题标题】:Extracting vertices from SceneKit iOS13 Swift 5从 SceneKit iOS13 Swift 5 中提取顶点
【发布时间】:2020-03-20 07:34:44
【问题描述】:

将我的代码更新到 iOS 13Swift 5,我收到了这个弃用警告

'withUnsafeBytes' 已弃用:改用 withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R

通过这段代码从 SCNGeometry 中提取顶点:

/// Extracts vertices from SCNGeometry
func vertices() -> [SCNVector3] {
    let vertexSources = self.sources(for: SCNGeometrySource.Semantic.vertex)
    if let vertexSource = vertexSources.first {
        let count = vertexSource.data.count / MemoryLayout<SCNVector3>.size
        return vertexSource.data.withUnsafeBytes {
             [SCNVector3](UnsafeBufferPointer<SCNVector3>(start: $0, count: count))
        }
    }
    return []
}

问题在于以下几行:

return vertexSource.data.withUnsafeBytes {
    [SCNVector3](UnsafeBufferPointer<SCNVector3>(start: $0, count: count))
}

This answer 在此处发布了解决方案,但没有 Swift 5 代码,我无法为警告提出解决方案。

This other answerthis thread 似乎提供了解决方案,但仅适用于 UInt32 类型的值,而不是 [SCNVector3] (array)

谢谢大家,我卡住了。

【问题讨论】:

    标签: swift scenekit ios13 swift5 deprecation-warning


    【解决方案1】:

    您可以通过将这些行替换为

    来消除警告
    return vertexSource.data.withUnsafeBytes { (buffer) in
        [SCNVector3](buffer.bindMemory(to: SCNVector3.self))
    }
    

    也就是说此代码已损坏。永远不要假设SCNGeometySource 中包含的数据布局(例如假设直接映射到SCNVector3)。 vectorCountfloatComponentscomponentsPerVectorbytesPerComponentdataOffsetdataStride 是正确检查属性源所必需的。

    【讨论】:

    • 似乎工作得很好。我假设您强调的问题,它也在代码的弃用版本中,因为它假设组件为MemoryLayout&lt;SCNVector3&gt;.size。因此,我将按照您的建议以更安全的方式工作。非常感谢!
    • 是的,我的评论比这个问题中讨论的警告更笼统。两个版本都很脆弱。
    猜你喜欢
    • 1970-01-01
    • 2013-08-03
    • 2013-06-19
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2015-12-25
    • 2017-02-01
    相关资源
    最近更新 更多