gpt4 book ai didi

function - Xcode (Swift) 使用另一个函数中的变量

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

我有一个计时器,当您按下按钮时它就会启动。

生成一个随机数,当达到随机数(1-100)时,时间应该停止。

我可以让它工作的唯一方法是在时间函数(计数)中生成随机数,但是每次计数器增加时都会生成一个随机数,这意味着只有当随机数生成相同的值时才会停止作为柜台。如果随机数和时间不落在同一个数字上,时间就会超过 100 - 我通过放入标签来显示随机数发现了这一点。

我已经设法通过将随机数放入按钮函数中来生成一次,但是计时器函数无法识别 stopNumber。这种方式似乎是最实用的,如何在计数函数中调用按钮函数中的变量stopNumber?

代码如下:

func generateNewNumber() -> UInt32 {
return arc4random_uniform(100) + 1

}


func Counting() {

var stopNumber:Int = Int(generateNewNumber())

timerCount += 1
timerLabel.text = "\(timerCount)"

if timerCount == stopNumber {
timer.invalidate()
timerRunning = false
}

@IBAction func startButton(sender: UIButton) {


if timerRunning == false && timerCount == 0 {
timer = NSTimer.scheduledTimerWithTimeInterval(0.06, target: self, selector: Selector("Counting"), userInfo: nil, repeats: true)
timerRunning = true
}

}

我对此还很陌生,任何帮助将不胜感激。

最佳答案

共享变量的方法有多种。

  1. 在方法外部创建一个变量,这样做:

    class myClass {
    var myVariable = 0
    myMethod() {/*use variable here*/}
    anotherMethod() {/*use variable here too*/}
    }
  2. 您可以在类外部创建变量,这甚至可以使其可供其他类访问:

    var myVariable = 0

    class myClass {
    myMethod() {/*use variable here*/}
    anotherMethod() {/*use variable here too*/}
    }
  3. 调用方法时可以将变量作为参数传递:

    myMethod() {
    var variable = 0
    anotherMethod(variable) {/*use variable here*/}
    }
    anotherMethod(var variab) {/*use 'variab' here*/}

    这相当不方便,这就是为什么我更喜欢使用其他之一。

希望对你有帮助:)

关于function - Xcode (Swift) 使用另一个函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30245134/

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