Swift 中的静态函数变量 [英] Static function variables in Swift

查看:19
本文介绍了Swift 中的静态函数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何在 Swift 中声明一个仅在本地作用域为函数的静态变量.

I'm trying to figure out how to declare a static variable scoped only locally to a function in Swift.

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

In C, this might look something like this:

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

在 Objective-C 中,基本相同:

In Objective-C, it's basically the same:

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

但我似乎无法在 Swift 中做这样的事情.我尝试通过以下方式声明变量:

But I can't seem to do anything like this in Swift. I've tried declaring the variable in the following ways:

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

但这些都会导致错误.

  • 第一个抱怨静态属性只能在类型上声明".
  • 第二个抱怨预期声明"(static 是)和预期模式"(timesCalledB 是)
  • 第三个抱怨一行中的连续语句必须用‘;’分隔"(在冒号和 static 之间的空格中)和预期类型"(其中 static代码>是)
  • 第四个抱怨一行上的连续语句必须用 ';' 分隔"(在 Intstatic 之间的空间中)和预期声明"(在等号)
  • The first complains "Static properties may only be declared on a type".
  • The second complains "Expected declaration" (where static is) and "Expected pattern" (where timesCalledB is)
  • The third complains "Consecutive statements on a line must be separated by ';'" (in the space between the colon and static) and "Expected Type" (where static is)
  • The fourth complains "Consecutive statements on a line must be separated by ';'" (in the space between Int and static) and "Expected declaration" (under the equals sign)

推荐答案

我认为 Swift 不支持静态变量而不将其附加到类/结构.尝试使用静态变量声明一个私有结构.

I don't think Swift supports static variable without having it attached to a class/struct. Try declaring a private struct with static variable.

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

这篇关于Swift 中的静态函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆