Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift String Interpolation displaying optional?

When i use the following code and have nameTextField be "Jeffrey" (or any other name)

@IBAction func helloWorldAction(nameTextField: UITextField) {

    nameLabel.text = "Hello, \(nameTextField.text)"

}

nameLabel displays... Hello, Optional("Jeffrey")

But, when I change the previous code to include a "!" like this:

@IBAction func helloWorldAction(nameTextField: UITextField) {

    nameLabel.text = "Hello, \(nameTextField.text!)"

}

The code works as expected and nameLabel displays.... Hello, Jeffrey

Why is the "!" required, in the video tutorial I used to create this simple program he did not use the "!" and the program worked as expected.

like image 954
Jeffrey Du Bois Avatar asked Jul 14 '15 21:07

Jeffrey Du Bois


2 Answers

Another alternative is to use the null coalescing operator within the interpolated string for prettier text without the need for if let.

nameLabel.text = "Hello, \(nameTextField.text ?? "")"

It's less readable in this case, but if there were a lot of strings it might be preferable.

like image 131
Craig McMahon Avatar answered Nov 02 '22 22:11

Craig McMahon


Optionals must be unwrapped. You must check for it or force unwrap as you do. Imagine the optional as a box where you put a value. Before you can access it, you need to put it out.

if let name = nameTextField.text {
    nameLabel.text = "Hello, \(name)"
}
like image 20
Tomáš Linhart Avatar answered Nov 03 '22 00:11

Tomáš Linhart