简体   繁体   English

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

[英]How to access an 'outside' variable in a class func in swift?

I have declared a class function in Swift and I wish to be able to access a certain variable in this function which has been declared outside. 我在Swift中声明了一个类函数,我希望能够访问此函数中已声明为外部的某个变量。

var something : Int = 0

and

class func add()
{
}

So I wish to access the value of 'something' in this class func. 所以我希望在这个类func中访问'something'的值。

Sorry if I sound stupid, still a bit new to Swift so please bear with me. 对不起,如果我听起来很愚蠢,对Swift来说还是有点新鲜所以请耐心等待。

You should understand what is class func, this is kind of the same as static func with a small difference with overriding rules. 您应该了解什么是类func,这与静态函数相同,与覆盖规则的差别很小。

if you want to access var something : Int you need to create an instance of that class. 如果你想访问var something : Int你需要创建该类的实例

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

static variable is a global variable, that can be accessed without creating an instance. static variable是一个全局变量,可以在不创建实例的情况下访问它。

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

you have to set the value to a static variable when declaring it (or setting a nil as optional) 在声明它时将值设置为静态变量(或将nil设置为可选)

static var something : int //this will not compile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM