简体   繁体   中英

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.

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. 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. 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)

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

Just to give you the general idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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