我正在尝试从 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/