Reputation: 359
Essentially, I have one function wherein several objects have been created, and another function where I am trying to access these objects. As seen below:
func createButtons() {
var myButton01 = BigButton.createbutton()
var myButton02 = BigButton.createbutton()
}
As you can see I am trying to access the objects to pair them up with keys in a dictionary.
func setupConstraints() {
var myButtonDictionary = ["myButton01": myButton01, "myButton02": myButton02]
...
}
How would I go about making them accessible without having to move the second function into the first function. Is there any way to make the objects accessible to other functions?
Upvotes: 0
Views: 181
Reputation: 26
Make myButton01 and myButton02 properties of the class you're working in, or if there is no class, just put the variables outside the functions.
This is how you would do it if there was no class:
var myButton01: BigButton? = nil
var myButton02: BigButton? = nil
func createButtons() {
var myButton01 = BigButton.createbutton()
var myButton02 = BigButton.createbutton()
}
func setupConstraints() {
var myButtonDictionary = ["myButton01": myButton01!, "myButton02": myButton02!]
...
}
Upvotes: 1
Reputation: 21003
Typically you would have these functions in some other construct, like a class and those objects would be instance variables.
class BigButton {
class func createButton() -> BigButton {
return BigButton()
}
}
class Foo {
var myButton01: BigButton?
var myButton02: BigButton?
func createButtons() {
myButton01 = BigButton.createButton()
myButton02 = BigButton.createButton()
}
func setupConstraints() {
var myButtonDictionary = ["myButton01": myButton01, "myButton02": myButton02]
}
}
Upvotes: 0