0

I have following Code in my Playground:

import GameplayKit
class TestClass {
    var sm: GKStateMachine

    init() {
        sm = GKStateMachine(states: [MyState()])
        sm.enter(MyState.self)
    }
}

class MyState: GKState {

    override init() {
        super.init()
    }
    override func didEnter(from previousState: GKState?) {
        printStateM()
    }
    func printStateM() {
        if (self.stateMachine == nil) {
            print("StateMachine")
        } else {
            print("No StateMachine")
        }
    }
}

var t = TestClass()

The output is "No StateMachine". I wonder why the StateMachine Property of MyState is nil?

Ragnar
  • 45
  • 7
  • Shouldn't that be `self.stateMachine != nil`? (or if you're planning to work with the variable, you probably want `if let stateMachine = self.stateMachine` or something like that) – John Montgomery Apr 18 '19 at 23:05

1 Answers1

0

Because you made a typo:

import GameplayKit
class TestClass {
    var sm: GKStateMachine

    init() {
        sm = GKStateMachine(states: [MyState()])
        sm.enter(MyState.self)
    }
}

class MyState: GKState {

    override init() {
        super.init()
    }
    override func didEnter(from previousState: GKState?) {
        printStateM()
    }
    func printStateM() {
        if (self.stateMachine != nil) { // ⚠️
            print("StateMachine")
        } else {
            print("No StateMachine")
        }
    }
}

var t = TestClass()

better yet, you can actually print it:

import GameplayKit
class TestClass {
    var sm: GKStateMachine

    init() {
        sm = GKStateMachine(states: [MyState()])
        sm.enter(MyState.self)
    }
}

class MyState: GKState {

    override init() {
        super.init()
    }

    override func didEnter(from previousState: GKState?) {
        printStateM()
    }

    func printStateM() {
        if let stateMachine = self.stateMachine {
            print("StateMachine: \(stateMachine)")
        } else {
            print("No StateMachine")
        }
    }
}

var t = TestClass()
Alexander
  • 59,041
  • 12
  • 98
  • 151