Swift:变量的值是公共(public)的但仍然是本地的?

标签 swift function class variables

我更改了一个函数中的值,并想访问同一类中另一个函数中的值。我的代码:

class person{

var fieldsWidth = CGFloat()
var xPos = CGFloat()
var yPos = CGFloat()
var player = SKSpriteNode()

func addPlayer(gameScene: GameScene, x: CGFloat, y: CGFloat){
    fieldsWidth = gameScene.screenWidth / CGFloat(hintergrund().fieldsX)
    player = SKSpriteNode(imageNamed: "player")
    player.size = CGSize(width: fieldsWidth, height: fieldsWidth)
    player.position = CGPoint(x: x, y: y)
    gameScene.addChild(player)
    xPos = x
}

func move(gameScene: GameScene, point: CGPoint, fWidth: CGFloat){
    print(xPos)
}

和游戏场景:

class GameScene: SKScene {

var screenWidth = CGFloat()
var screenHeight = CGFloat()
var touchLocation = CGFloat()
var fieldsWidth = CGFloat()
let player = person()

override func didMoveToView(view: SKView) {
    screenWidth = self.size.width
    screenHeight = self.size.height
    fieldsWidth = screenWidth / CGFloat(hintergrund().fieldsX)
    person().addPlayer(self, x: fieldsWidth/2, y: fieldsWidth/2)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    /* Called when a touch begins */
    let touch =  touches.first
    var point = CGPoint()
    point = touch!.locationInNode(self)
    player.move(self, point: point, fWidth: fieldsWidth)
}

}

不知何故,xPos 的值只是在 addPlayer 中的本地值。如何正确访问 xPos 的值?希望你能帮助我。

最佳答案

以下代码在 XCode Version 7.1 (7B91b) playground 中完全按照我的预期运行

class person{

    var yPos = CGFloat()

    func function1(y: CGFloat){
        yPos = y
        print(yPos)  //Value of yPos is 31.25; correct!
    }

    func function2(){
        print(yPos)  //Value of yPos is 0.0; wrong!??
    }
}

let foo = person()
foo.function1(31.25)
foo.function2() //Outputs 31.25

关于Swift:变量的值是公共(public)的但仍然是本地的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593962/

相关文章:

ios - 动画在某些 View Controller 中不起作用

ios - iTunes 连接 : Invalid Swift Support - framework doesn’t have the correct file type for this location

swift - XCUITest 无法识别警报

ios - 如何告诉 iOS 11 中的 Smart Invert 不要反转我的应用程序颜色并检测它是否已启用?

ios - 当你在第一个 VC 中时,如何在第二个 VC 中运行一个函数?

PHP 将一个数组附加到另​​一个数组(不是 array_push 或 +)

C - 将 9 转为 0

ruby - Ruby 1.9 中的 ARGF.class 是什么?

c++ - 如何解决字段 'classname'有不完整的类型错误

android,如何获取包名?