Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Simen Anthonsen
1,097 PointsArray of UITextfields
If i create an array of textfields like this
var textfields = [textfield1, textfield2]
I get an error saying " Instance member "textfield1" cannot be used on type viewController.
It works if i create the array inside of a function, but it is necessary to have the array outside of the a function.
Simen Anthonsen
1,097 PointsI need to be able to modify(append and remove) the array by the help of other functions. I can´t do that if var textfields is a local. I need it to be an instance variable.
Caleb Kleveter
Treehouse Moderator 37,862 PointsIf you are only appending and removing you should be fine creating the array in the viewDidLoad. Guess I was wrong.
Simen Anthonsen
1,097 PointsIf I do as you say and create the array in the viewdidload, I won´t be able to for example remove a textfield by pushing a button.
1 Answer
Richard Lu
20,185 PointsHey Simen,
Have you tried using property observers on your textfields since it must be outside the function?
var textfields = [UITextField]()
var textfield1: UITextField! { didSet { textfields.append(textfield1) } }
var textfield2: UITextField! { didSet { textfields.append(textfield2) }}
The reason you may be getting that error is because the textfields are not initialized until run time.
- Rich
Simen Anthonsen
1,097 PointsThanks!
Caleb Kleveter
Treehouse Moderator 37,862 PointsCaleb Kleveter
Treehouse Moderator 37,862 PointsWhy does it have to be outside of a function? Why can't you put it in the
viewDidLoad?