swift - 使用超出其范围的变量

标签 swift scope

我希望访问其范围之外的变量。 (发布了相关代码片段)。在 @IBAction 中,无法识别 sphereNode.runAction(moveUp)。

我不能简单地将 sphereNode 声明为全局,因为它依赖于 sphereGeometry 声明。

override func viewDidLoad() {
    super.viewDidLoad()

    //Added our first shape = sphere
    let sphereGeometry = SCNSphere(radius: 1.0)
    let sphereNode = SCNNode(geometry: sphereGeometry)
    sphereNode.position = SCNVector3Make(0, 0, 0)
    sphereGeometry.firstMaterial!.diffuse.contents = UIColor.redColor()
    sphereGeometry.firstMaterial!.specular.contents = UIColor.whiteColor()
    scene.rootNode.addChildNode(sphereNode)
}

@IBAction func animateButton(sender: AnyObject) {
    let moveUp = SCNAction.moveByX(0.0, y: 1.0, z: 0.0, duration: 1.0)
    sphereNode.runAction(moveUp)
}

}`

初学者程序员,所以请简单的解释 - 提前致谢。

最佳答案

这里您需要的是一个实例变量。

变量不能在其范围之外使用(最终你会发现这是一件非常棒的事情)。但我们可以扩展变量的范围:

class YourViewController: UIViewController {
    var sphereNode: SNNode?

    override func viewDidLoad() {
        super.viewDidLoad()

        //Added our first shape = sphere
        let sphereGeometry = SCNSphere(radius: 1.0)
        self.sphereNode = SCNNode(geometry: sphereGeometry)
        self.sphereNode?.position = SCNVector3Make(0, 0, 0)
        sphereGeometry.firstMaterial!.diffuse.contents = UIColor.redColor()
        sphereGeometry.firstMaterial!.specular.contents = UIColor.whiteColor()
        scene.rootNode.addChildNode(sphereNode)
    }

    @IBAction func animateButton(sender: AnyObject) {
        let moveUp = SCNAction.moveByX(0.0, y: 1.0, z: 0.0, duration: 1.0)
        self.sphereNode?.runAction(moveUp)
    }
}

关于swift - 使用超出其范围的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30733031/

相关文章:

scala - 在 Scala 中,我如何显式引用封闭的本地范围?

swift - 以编程方式更改状态时可以动画 NSSwitch 吗?

swift - 在 Swift 中检索 parse.com 数据

javascript - 文档就绪函数内的全局范围

haskell - 如何在 where 子句中使用 do block 赋值行中的变量?

关于变量作用域规则的Python问题

c++ - 在 C++ 中,通过引用扩展作用域安全吗?

swift - 无法将整个双向链表元素打印到控制台

ios - swift (xcode 9 : code works in tutorial video):unexpectedly found nil while unwrapping an Optional value

swift - 不支持的架构.frameworks