Search code examples
swiftenumsskscene

The following code works when I manually pass the value but fails when I unwrap the value


I just started learning Swift as my first coding language. My current challenge is trying to automate the transitions from a current level setup as LevelOne.sks to another level also created in Xcode level editor as LevelTwo.sks. What I'm attempting to do is trigger a transition to the next level with the following set of code.

In my base scene I have this function to send the player to the next level

private func goToNextLevel(nextLevel: String) {

    //When hard coding the arguments as... 
    //loadScene(withIdentifier: .levelTwo)
    //The level two scene loads and is playable...however,
    //When trying to change the level argument in code
   // by passing a nextLevel variable
   // the optional unwraps nil and crashes the app.

    loadScene(withIdentifier: SceneIdentifier(rawValue: nextLevel)!)

}

This is then passed to a SceneLoadManager File

  enum SceneIdentifier: String {
    case levelOne = "LevelOne"
    case levelTwo = "LevelTwo"
//    case levelThree = "LevelThree"
}

private let sceneSize = CGSize(width: 768, height: 1024)

protocol SceneManager { }
extension SceneManager where Self: SKScene {

    func loadScene(withIdentifier identifier: SceneIdentifier) {


        let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
        let nextLevel = SKScene(fileNamed: identifier.rawValue)
        nextLevel?.scaleMode = .aspectFill
        self.view?.presentScene(nextLevel!, transition: reveal)
    }

I think this has something to do with how I'm trying to set nextLevel. Currently I'm setting this up as follows

let nxtLvl = String?
nxtLvl = ".levelOne"
goToNextLevel(nextLevel: nxtLvl)

Hopefully you can make sense of what I'm trying to achieve and that I'm at least close to being on the right track here. Any help would be greatly appreciated. Thanks!


Solution

  • What could really help you to solve :

    SceneIdentifier.levelOne.rawValue returns this -> "LevelOne"

    BUT

    SceneIdentifier(rawValue : "LevelOne") returns -> SceneIdentifier.levelOne

    See the difference ? In the first you get the string , in that case what you want And in the second you get the "left member" (I don't know the therm)

    An example to see clearer if you have an enum :

    enum SceneIdentifier: String {
        case case1 = "LevelOne"
        case case2 = "LevelTwo"
    
    }
    

    SceneIdentifier(rawValue : "LevelOne") !

    returns this : SceneIdentifier.case1

    and SceneIdentifier.case1.rawValue returns this : "levelOne"