Reputation: 65
When declaring global variables, where is the "best practice" place to initialize them in the code?
I have a button that I would like to declare as a constant but in doing so would have to initialize it at the top of the code file, which I've been taught and seen isn't the best option.
I'm having a hard time reconciling putting something like this in a global scope.
let button = UIButton(frame: CGRectMake(0,0,64,49))
One option would be to change it to a var and just reinitialize like this:
var button = UIButton()
Then later in a given function do:
button = UIButton(frame: CGRectMake(0,0,64,49))
but this seems like a waste initializing twice.
Thoughts?
Upvotes: 3
Views: 1829
Reputation: 5451
You can declare it as optional:
var button: UIButton?
and initialize it later:
button = UIButton(frame: CGRectMake(0,0,64,49))
Upvotes: 5