How do you "add" two text fields?

Ok, so in my app I have got two textfields, one label and one button. I manage to get the content of the one textfield to be displayed in the label, but i want to display the content of both of the textfields.


@IBAction func buttonPushed(sender: UIButton) {
        Label.text = "\(textfield1.text)"
        + "\(textfield2.text)"


The code above is the closest I´ve com, but the Label displays: Optional"whatever i typed in the textfield"Optional"whatever i typed in the textfield"

Why would it do that?


You must know what an optional is in order to answer your question. There are many free good resources to learn about them, Apple's own book on Swift being the best place to start, I believe.


I do not think adding text fields makes sense; it is the text that is being "added". I'd probably create the necessary extensions to do this:

[textfield1.text, textfield2.text].flatMapped.sum

Definitely read about Optionals, this is an important concept in Swift. Since the default value of text in UITextField is "" and it reverts to "" even if it is explicitly set to nil (at least in Xcode 7.1 beta 3 playground), in this particular situation, the easiest solution might be forced unwrapping:


let text = "\(textField1.text!)"
    + "\(textField2.text!)"


In fact, you don't need to use the +:


let text = "\(textField1.text!) \(textField2.text!)"

Here is a more DRY solution.


extension SequenceType where Generator.Element == String {
  var concatenation: String {return reduce("", combine: +)}
}

[textfield1, textfield2].flatMap {$0.text} .concatenation
How do you "add" two text fields?
 
 
Q