swift - SCNGeometryElement 在 Swift 3 中的设置

标签 swift cocoa swift3 scenekit

我硬着头皮开始将我的应用程序转换为 Swift 3。与往常一样,转换器还有很多不足之处。在这种情况下,我不确定如何正确编写新版本的代码。原文如下:

let indexes : [CInt] = [0,1,2,3]
let dat  = NSData(bytes: indexes, length: sizeofValue(indexes))
let ele = SCNGeometryElement(data:dat, primitiveType: .Triangles, primitiveCount: 2, bytesPerIndex: sizeof(Int))

运行转换并编写新的 sizeof(感谢)后,我得到了这个:

let indexes : [CInt] = [0,1,2,3]
let dat  = Data(bytes: UnsafePointer<UInt8>(indexes), count: sizeof(indexes))
let ele = SCNGeometryElement(data:dat, primitiveType: .triangles, primitiveCount: 2, bytesPerIndex: MemoryLayout<Int>.size)

但是,这给了我(在 Data(bytes:length:) 调用中):

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

我已经查看了这里的几个主题,并阅读了涵盖此内容的发行说明,但我仍然对我应该在这里做什么感到困惑。

最佳答案

您修复了一个 sizeof 但没有修复另一个,并且您正在创建一个不必要的新指针 — 任何数组(给定正确的元素类型)都可以传递给采用 C-风格指针。然后,您的代码的直接修复是:

let indexes: [CInt] = [0,1,2,3]
let dat = Data(bytes: indexes, count: MemoryLayout<CInt>.size * indexes.count)
let ele = SCNGeometryElement(data:dat, primitiveType: .triangles, primitiveCount: 2, bytesPerIndex: MemoryLayout<CInt>.size)

(另请注意使您的 MemoryLayout 与它们描述的数据一致的修复。)

但是,除非您需要额外的 Data 对象,为了有趣的指针,或者为了描述您的元素的额外特异性,您可以使用更简单的形式:

let indices: [UInt8] = [0,1,2,3] 
let element = SCNGeometryElement(indices: indices, primitiveType: .triangles)

This generic initializer在进来的路上自动管理内存,推断出数组的个数,根据数组的个数和你指定的primitiveType推断出primitiveCount

(请注意,包含四个索引的数组对于 .triangles 来说是一个不寻常的数字;要么您有一个三角形和一个未使用的索引,要么您实际上是指 .triangleStrip包含两个基元。)

关于swift - SCNGeometryElement 在 Swift 3 中的设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40898966/

相关文章:

macos - 您如何使用 Swift 在 Cocoa 应用程序的 View 之间导航?

ios - Swift 3 通用参数

ios - 从 UnitTest 启动 ViewDidAppear

swift - 重用安全范围书签

swift - 如何将 child SKSpriteNode 定位在他们的 parent 里面

ios - 错误为 "touchesBegan"

swift - 在 Swift 3 中计算范围计数

cocoa - 告诉 Clang Static Analyzer 有关拥有引用的第三方库的信息

cocoa - 自定义 NSWindowController 子类

iphone - 适用于 iOS 和 Mac OS X 的跨平台方法是什么?