Swift 按类型转换(自我)
是否可以创建一个类别(扩展名),最终返回一个被强制转换为Swift 按类型转换(自我),swift,Swift,是否可以创建一个类别(扩展名),最终返回一个被强制转换为instancetype的对象?我有一个类别来加载SKS文件,但由于该类别用于SKNode,因此所有其他子类,如SKScene或skimiternode,等等。。我也会采纳它 因此,我只想避免总是从SKNode强制转换为instancetype。是否可以将返回类型更改为instancetype,并确保编译器对返回值满意 我想我可以使用->Self作为返回类型,但是我不知道如何将场景转换为instancetype,这样这个东西就可以编译了 例
instancetype
的对象?我有一个类别来加载SKS文件,但由于该类别用于SKNode
,因此所有其他子类,如SKScene
或skimiternode
,等等。。我也会采纳它
因此,我只想避免总是从SKNode
强制转换为instancetype
。是否可以将返回类型更改为instancetype
,并确保编译器对返回值满意
我想我可以使用->Self
作为返回类型,但是我不知道如何将场景
转换为instancetype,这样这个东西就可以编译了
例如:
SKEmitterNode.unarchiveFromFile(“Blah”)
将返回SKEmitterNode的实例
extension SKNode {
class func unarchiveFromFile(file: String) -> SKNode {
let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks")
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
let unarchiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
unarchiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = unarchiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as SKNode
unarchiver.finishDecoding()
return scene
}
}
这可能对你有用。我不能测试它,因为我没有太多的经验
斯皮特基特。但它确实编译并使用编译器推断的类型
let e = SKEmitterNode.unarchiveFromFile("Blah")
这是斯基米特诺德。其思想是定义一个通用的辅助函数
func unarchiveFromFileHelper<T where T : SKNode>(file: String) -> T
使用T==Self
调用helper函数
extension SKNode {
class func unarchiveFromFile(file: String) -> Self {
func unarchiveFromFileHelper<T where T : SKNode>(file: String) -> T {
let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks")
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
let unarchiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
unarchiver.setClass(T.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = unarchiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as T
unarchiver.finishDecoding()
return scene
}
return unarchiveFromFileHelper(file)
}
}
从SKNode
超类,例如
if let e = SKEmitterNode(fileNamed: "Blah") {
// ...
}
您可以将->SKNode
更改为->Self
并将作为SKNode
更改为作为Self
吗?我可以在定义中将SKNode更改为Self,但最终无法将场景
转换为Self。您在objc中的instancetype可能也有相同的问题:)对;在Objective-C中,您可以在类方法中使用self
,或在实例方法中使用[self class]
。虽然此代码有效,但swift编译器只是在发布版本中因seg错误而崩溃:),但将内部函数作为私有类函数移到外部可以解决问题。
convenience init?(fileNamed filename: String)
if let e = SKEmitterNode(fileNamed: "Blah") {
// ...
}