简体   繁体   English

如何快速访问函数外部的变量

[英]How do you access a variable outside a function in swift

I am trying to access inputAC and inputB outside my function getVariables and I can't seem to get it working. 我正在尝试在函数getVariables之外访问inputAC和inputB,但似乎无法正常工作。

Here is the code I am working with but it does currently work. 这是我正在使用的代码,但目前可以使用。

func getVariables () {
        var inputAC = textFieldAC.text.toInt()
        var inputB = textFieldB.text.toInt()

    }

    var ac = inputAC
    var b = inputB

Anyone have any ideas? 有人有想法么?

Thanks 谢谢

You need to return the values from the function. 您需要从函数返回值。 Here is one way to do it by returning them in a tuple: 这是通过将它们返回到元组来实现的一种方法:

func getVariables () -> (Int?, Int?) {
    var inputAC = textFieldAC.text.toInt()
    var inputB = textFieldB.text.toInt()
    return (inputAC, inputB)
}

var (ac, b) = getVariables()

// Since the values are optionals, you can use optional binding to
// safely unwrap the value.
if let acval = ac {
    println("ac value is \(acval)")
} else {
    println("alas, ac was nil")
}

These variables which are in getVariables method can not be access outside this method, because these are method local variables. getVariables方法中的这些变量不能在此方法外部访问,因为它们是方法局部变量。 Scope for accessing them is only for that method. 访问它们的范围仅适用于该方法。 If you want to access them declare them as property or instance variables in class.... 如果要访问它们,请在类中将它们声明为属性或实例变量。

I would suggest you to instance this variables in class. 我建议您在课堂上实例化此变量。 If swift is not so different to java, you could declare them as class variables and set them in your method. 如果swift与Java没有太大不同,则可以将它们声明为类变量,然后在方法中进行设置。 Then, outside your method, you could access them with a 然后,在您的方法之外,您可以使用

(this is java code, I'm sorry, but I try to give you the general idea) (这是java代码,很抱歉,但是我尝试为您提供大致的想法)

In the class you should do something like this: 在课堂上,您应该执行以下操作:

Int ac; int b;

In the method do something like this: 在方法中执行以下操作:

this.setInputAc(inputAc);
this.setInputB(inputAc);

Outside you should do something like this: 在外面,您应该执行以下操作:

ac = this.getInputAc();  
b = this.getInputB();

Also, declare your setter and getter for each variable 另外,为每个变量声明您的setter和getter

Just to give you the general idea. 只是为了给您大致的想法。

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

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