繁体   English   中英

如何在Swift中制作一个使用“自我”的全局变量

[英]How to make a global variable that uses “self” in Swift

您好,我目前在xCode中使用swift,并且我有一个随机数生成器,该生成器在视图中生成一个随机点。

        func randomInRange(lo: Int, hi : Int) -> Int {
            return lo + Int(arc4random_uniform(UInt32(hi - lo + 1)))
        }
        // x coordinate between MinX (left) and MaxX (right):
        let randomX = randomInRange(Int(CGRectGetMinX(self.frame) * 2), Int(CGRectGetMaxX(self.frame)))
        // y coordinate between MinY (top) and MidY (bottom):
        let randomY = randomInRange(Int(CGRectGetMinY(self.frame) * 2), Int(CGRectGetMaxY(self.frame)))
        let randomPoint = CGPoint(x: randomX , y: randomY)

我想全局使用此变量,以便我可以多次使用此随机点,而不是每次都必须写出整个代码块。 现在我知道您可以通过在GameScene类之上或在类与viewDidLoad之间声明它来创建全局变量,例如

class GameScene: SKScene , SKPhysicsContactDelegate {


func randomInRange(lo: Int, hi : Int) -> Int {
    return lo + Int(arc4random_uniform(UInt32(hi - lo + 1)))
}
// x coordinate between MinX (left) and MaxX (right):
let randomX = randomInRange(Int(CGRectGetMinX(self.frame) * 2), Int(CGRectGetMaxX(self.frame)))
// y coordinate between MinY (top) and MidY (bottom):
let randomY = randomInRange(Int(CGRectGetMinY(self.frame) * 2), Int(CGRectGetMaxY(self.frame)))
let randomPoint = CGPoint(x: randomX , y: randomY)


 override func didMoveToView(view: SKView) {
    /* Setup your scene here */

但是,当我将其放在同一场景类上方时,会收到错误消息...“使用未解决的标识符自身”,当我将其放置在gameScene类和viewDidLoad之间时,会出现错误... gameScene没有名为的成员自我。 如果可能的话,可以使用其他方法代替视图本身,如果可以,请回答。 谢谢 !

在GameScene类之上声明全局函数,并用UIScreen.main.bounds替换self.frame

您可以像这样使用单例:

class MyGlobalCounters {
  var counter = 0
  var this = "Hello"
  var that:CGFloat = 1.23

  class var sharedInstance : MyGlobalCounters {
    return _SingletonSharedInstance
  }
}
private let _SingletonSharedInstance = MyGlobalCounters()


class A {
  let myGlobalCounters = MyGlobalCounters.sharedInstance
  func dumpAndInc() {
    println("ctr=\(myGlobalCounters.counter++)")
  }
}

class B {
  let myGlobalCounters = MyGlobalCounters.sharedInstance
  func dumpAndInc() {
    println("ctr=\(myGlobalCounters.counter++)")
  }
}
let a = A()
let b = B()
a.dumpAndInc() 
b.dumpAndInc() // in b we use the same instance for the counters
a.dumpAndInc() // as in a

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM