0

Updating my code to iOS 13 and Swift 5, I have this deprecated warning:

'withUnsafeBytes' is deprecated: use withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R instead

Over this fragment of code to extract the vertices from a 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 []
}

The problem lays inside this lines:

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

This answer gives solution here posted but there is no Swift 5 code, and I cannot come up with a solution for the warning.

This other answer and this thread seem to give a solution but for only a value of type UInt32 not an [SCNVector3] (array).

Thank you all, I'm stuck.

Jorge Frias
  • 1,077
  • 11
  • 13

1 Answers1

0

You can get rid of the warning by replacing these lines with

return vertexSource.data.withUnsafeBytes { (buffer) in
    [SCNVector3](buffer.bindMemory(to: SCNVector3.self))
}

That said this code is broken. One should never assume that the layout of the data contained in a SCNGeometySource (for instance assuming a direct mapping to SCNVector3). The vectorCount, floatComponents, componentsPerVector, bytesPerComponent, dataOffset and dataStride are necessary to correctly inspect a property source.

mnuages
  • 13,049
  • 2
  • 23
  • 40
  • Seems to work just fine. I asume the problem you highlight, it's in the deprecated version of the code too, because it's assuming `MemoryLayout.size` for the components. So I will work on a safer way as you recommend. Thank you very much! – Jorge Frias Nov 25 '19 at 19:27
  • yes, my comment was more general than the warning discussed in this question. Both versions are fragile. – mnuages Nov 25 '19 at 21:44