swift - 如何使用 SCNSceneSource 方法 entryWithIdentifier :classType:?

标签 swift scenekit

我正在尝试从 DAE 文件中提取动画,如何在 swift 中使用此方法?

谢谢,

Objective-C 代码是:

//CAAnimation *animation = [sceneSource entryWithIdentifier:animationIDs[index] withClass:[CAAnimation class]];

func extractAnimationsFromSceneSource(sceneSource: SCNSceneSource) {

    let animationsIDs: NSArray = [sceneSource.isKindOfClass(CAAnimation)]

    let animationCount: Int = animationsIDs.count
    var longAnimations = NSMutableArray(capacity: animationCount)

    let maxDuration: CFTimeInterval = 0

    for index in 0..animationCount {
// gets error CAAnimation is not convertible to 'AnyClass'
        let animation = sceneSource.entryWithIdentifier(animationsIDs[index], withClass:CAAnimation())
    }

}

最佳答案

这里有几个问题需要处理:

  • [SomeClass class] 的 Swift 等价物是 SomeClass.self
  • 因为 entryWithIdentifier 在 ObjC 中返回一个 id,您通常希望将其转换为适当的 Swift 类型(因为您不能调用方法或访问属性AnyObject)。
  • 如果没有找到条目,
  • entryWithIdentifier 可以在 ObjC 中返回 nil,这意味着它在 Swift 中返回一个可选的。桥接使它成为一个隐式解包的可选项,如果您计划将这些动画添加到数组或以其他方式使用它们,这会让您远离崩​​溃 — 最好自己检查可选项。

此外,您的 animationIDs 数组看起来很可疑 — 您正在为一个数组分配一个元素,一个 bool 值,它是询问场景源它是什么类的结果。 (并且此 bool 值始终为 false,因为 SCNSceneSource 不是一种 CAAnimation。)

因此,您的方法可能如下所示:

func extractAnimationsFromSceneSource(sceneSource: SCNSceneSource) {

    let animationsIDs = source.identifiersOfEntriesWithClass(CAAnimation.self) as String[]
    var animations: CAAnimation[] = []
    for animationID in animationsIDs {
        if let animation = source.entryWithIdentifier(animationID, withClass: CAAnimation.self) as? CAAnimation {
            animations += animation
        }
    }

}

(包括一些尝试推断您的意图,并在类型推断允许的情况下精简代码。)

关于swift - 如何使用 SCNSceneSource 方法 entryWithIdentifier :classType:?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24417182/

相关文章:

json - 追加不起作用

swift - 无法分配给值 : 'completionBlock is a ' let' constant

ios - 强制用户在导航之前在 TableView 中选择一行

ios - 无法正确检测多几何形状的碰撞

swift - 改变平面中顶点的位置

swift - 如何访问从 Firebase 下载的 SceneKit 文件?

ios - SceneKit SCNNode 初始化(mdlObject :) missing?

swift - 如何在 xCode 和 Swift 中用 xyz "forced cast"修复 "only unwraps and bridges"

c - 如何将一个很长的 C 宏桥接到 Swift?

ios - 当 viewContext.automaticallyMergesChangesFromParent 设置为 true 时,viewContext 指的是什么父级?