加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中的静态函数变量

发布时间:2020-12-14 06:10:32 所属栏目:百科 来源:网络整理
导读:我试图找出如何声明一个静态变量只有本地的一个函数在Swift中。 在C中,这可能看起来像这样: int foo() { static int timesCalled = 0; ++timesCalled; return timesCalled;} 在Objective-C中,它基本上是一样的: - (NSInteger)foo { static NSInteger tim
我试图找出如何声明一个静态变量只有本地的一个函数在Swift中。

在C中,这可能看起来像这样:

int foo() {
    static int timesCalled = 0;
    ++timesCalled;
    return timesCalled;
}

在Objective-C中,它基本上是一样的:

- (NSInteger)foo {
    static NSInteger timesCalled = 0;
    ++timesCalled;
    return timesCalled;
}

但我似乎不能在Swift中做这样的事情。我已经尝试声明变量在以下方式:

static var timesCalledA = 0
var static timesCalledB = 0
var timesCalledC: static Int = 0
var timesCalledD: Int static = 0

但这些都导致错误。

>第一个抱怨“静态属性只能在类型上声明”。
>第二个引用“Expected declaration”(其中static是)和“Expected pattern”(其中timesCalledB是)
>第三个引用“在一行上的连续语句必须用’;’”(在冒号和静态之间的空格)和“预期类型”(其中static是)
>第四个提示“在一行上的连续语句必须由’;’”(在Int和static之间的空格中)和“Expected declaration”(在等号下)

我不认为Swift支持静态变量,而没有它附加到一个类/结构。尝试声明一个带有静态变量的私有结构体。
func foo() -> Int {
    struct Holder {
        static var timesCalled = 0
    }
    Holder.timesCalled += 1
    return Holder.timesCalled
}

  7> foo()
$R0: Int = 1
  8> foo()
$R1: Int = 2
  9> foo()
$R2: Int = 3

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读