2015-04-22 61 views
0

您好我目前在xCode中使用swift,我有一個隨機數生成器,在視圖中產生一個隨機點。如何使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沒有一個名爲self的成員。 如果可能的話,是否有辦法將自己替換爲與視圖有關的其他東西,如果是這樣,請回答。 謝謝!

+1

使用一個單獨的類分享。 –

+0

你想使用這一次只計算屬性作爲全局常量或有可能在不同的控制器/視圖中多次計算它? – Kubba

+0

我不完全確定如何使用/創建單例類,我如何在一箇中實現我的隨機點?該班級在哪裏?謝謝托馬斯 –

回答

0

可以使用單是這樣的:

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