当前位置:首页 > 教育 > 正文

如何根据其他函数被调用的次数来操作开关函数?

提问开始:

我试图让swift以一种方式来执行,即检测函数运行了多少次,然后基于此执行switch语句。

要做到这一点,理想的方法是让swift每次循环数组中的一个元素,然后在下一次调用函数时遍历下一个元素,然后再遍历下一个元素,但我不认为这是可行的。

//the doThing() function will perform after a certain condition is met
func doThing() {
var x = 0
switch x {
case: 0
doOtherThing()
x = 1
//and then I want this function to end and wait for the condition to be met to call the doThing() function, and then run the next pieces of code and so forth
case: 1
doOtherOtherThing()
x = 2
case: 2
doOtherOtherOtherThing()
default:
doNothing()
}

我需要帮助解决这个代码,因为它不工作。

回答开始:得票数 1

诀窍是将变量x移到函数外部:

var x = 0
func doThing() {
    switch x {
        case: 0
            doOtherThing()
        case: 1
            doOtherOtherThing()
        case: 2
            doOtherOtherOtherThing()
        default:
            doNothing()
    }
    x += 1
}

您还可以将x设为fileprivate (如果函数在全局作用域中)或private (如果函数在结构或类中),这样其他代码就不能(意外地)更改它。

总结

以上是真正的电脑专家为你收集整理的如何根据其他函数被调用的次数来操作开关函数?的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得真正的电脑专家网站内容还不错,欢迎将真正的电脑专家推荐给好友。

有话要说...

取消
扫码支持 支付码