gpt4 book ai didi

swift - GKState : Why is self. 状态机 == nil?

转载 作者:行者123 更新时间:2023-11-30 10:46:03 25 4
gpt4 key购买 nike

我的 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()

输出为“无状态机”。我想知道为什么MyState的StateMachine属性是nil?

最佳答案

因为你打错了:

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()

更好的是,您实际上可以打印它:

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()

关于swift - GKState : Why is self. 状态机 == nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55754717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com