如何在swift中的类func中访问“outside”变量?

时间:2015-08-24 06:16:34

标签: swift

我在Swift中声明了一个类函数,我希望能够访问此函数中已声明为外部的某个变量。

var something : Int = 0

class func add()
{
}

所以我希望在这个类函数中访问'something'的值。

很抱歉,如果我听起来很愚蠢,对Swift来说还是有点新鲜,所以请耐心等待。

1 个答案:

答案 0 :(得分:7)

你应该理解什么是类func,这与静态函数有点相同,与覆盖规则的差别很小。

如果您想要访问var something : Int,则需要创建该类的实例

var classInstance = MyClass() //swift allocates memory and creates an instance
classInstance.something = 5

静态变量是一个全局变量,无需创建实例即可访问。

static var something : Int = 4
MyClass.something = 3 //didnt create instance of MyClass

在声明它时将值设置为静态变量(或将nil设置为可选)

static var something : int //this will not compile