Friday, September 20, 2019

Optional casting to a variable whose Type is a class type in Swift

I've looked for similar questions on Google and SO and couldn't find anything directly related. There seem to be two similar (maybe?) questions in C#, but I don't know the language, so I didn't really understand the questions properly (How to cast object to type described by Type class?, and Cast a variable to a type represented by another Type variable?).



I was experimenting with writing a generic scene-changing function in my GameViewController in SpriteKit. I made a SceneChangeType enum to use as a parameter. The error came in trying to optional cast a variable to what I expected to be a generic Type.



Just to clarify, I'm sure there are lots of reasons why this isn't a good idea. I can think of other ways to handle scene-changing, like just writing separate methods for each scene change. I'm just curious from a technical standpoint why I'm getting an error that I can't understand.



The relevant code is as follows:




In GameViewController.swift



func genericSceneChangeWithType(sceneChangeType: SceneChangeType) {
let expectedType = sceneChangeType.oldSceneType
guard let oldScene = self.currentScene as? expectedType else { return }
...
}

enum SceneChangeType {

case TitleSceneToGameScene
var oldSceneType: SKScene.Type {
switch self {
case .TitleSceneToGameScene:
return TitleScene.self
}
}
...
}



For clarification, TitleScene is a custom subclass of SKScene, and self.currentScene has type SKScene?.



On the line,



guard let oldScene = self.currentScene as? expectedType else { return }


I get the error,




'expectedType' is not a type


Am I just massively misunderstanding things here? I thought you could use similar syntax to return a generic type from a function (e.g. Swift: how to return class type from function).
Is the issue because it's a property?
Is this not even possible, or is there some other way to check the type if the expected type is not known until runtime?



To emphasise again, I'm not asking about better ways to change scenes, and I'm not sure I have any examples where this is absolutely necessary. But understanding why this doesn't work might help me, or others, to understand the workings of the language better.



Thank you.

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...