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 PointsConcatenate strings from UITextfields
What is the best way to concatenate strings that are written in UITextfields?
I have don managed this by doing it this way
var text = textfield1.text! + textfield2.text! + textfield3.text! + textfield4.text! + textfield5.text!
But is there a better way? Maybe making text an array or something?
1 Answer
Danny Yassine
9,136 PointsI would agree with Ian here, you must be careful when unwrapping the 'text' property of the UITextFields since they are optional values.
Add simple logic ('if let' or even a 'for-loop' to check ) that all UITextFields do contain texts.
I used String Interpolation for easily adding multiple strings together like below:
if (textfield1.text != nil && textfield2.text != nil && textfield3.text != nil && textfield4.text != nil && textfield5.text != nil) {
// Add strings together
var string = "\(textfield1.text) \(textfield2.text) \(textfield3.text) \(textfield4.text) \(textfield5.text)"
} else {
// Show some kind of error message
}
Simen Anthonsen
1,097 PointsThanks!
ianhan3
4,263 Pointsianhan3
4,263 PointsNot sure if there is necessarily a better way (probably is, I just don't know), however, I would caution against force unwrapping the text sans some sort of error checker. If one of the text fields is empty, your app will crash. If you're using a nav controller you could do something like this:
doneBarButton.enabled = (textFieldVariableName.length > 0)Or an if, else statement if you have multiple criteria. Sorry not a full answer to your question.