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

iOS

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

Why does it have to be outside of a function? Why can't you put it in the viewDidLoad?

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

If you are only appending and removing you should be fine creating the array in the viewDidLoad. Guess I was wrong.

If 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

Hey 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

Thanks!