简体   繁体   中英

How to call a constant from a func in another func

I'm new in swift and have a question 😊.

I made a UITextField in a func programmatically and I want to call it in another func like:

func alertForEmptyField {
    if textfield == nill { 
        ...
    }
}

But I can't call my textfield of course because it is in another func , but my silly question is how can I call it ?

I don't want to make my constants in viewDidLoad because those are more than 20 constants for that reason I made them separately in separate func .

Thank you so much.

You need to read up on the concept of scope. The Apple Swift iBook covers this quite well. I suggest reading the first few chapters of that book to get a better grounding. (You will struggle until you get this concept, so it's worth spending as much time as it takes to get it before moving on.)

If you define a variable or let constant inside a function, it is a local variable, and it ceases to exist when you exit the function. If that variable/constant contains an object, and that's the only reference to that object, it will get deallocated once the function returns. You need to move your variables/constants outside of your functions (and probably make them instance variables) if you want them to be accessible from other instance methods in your class.

You shouldn't do that. If you need to access variable you should return it. Then you can assign it to variable, constant or property.

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