Why is Optional(“Text”) - Swift

大城市里の小女人 提交于 2019-11-27 07:29:45

问题


I just started with Swift. So I created a simple application with a label, button and a text field. When you click the button, the app has to change the label with the text of the text field.

class ViewController: UIViewController {
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet weak var textField: UITextField!

    @IBAction func updateButton(sender: UIButton) {
        textLabel.text = "Hi \(textField.text) "
    }

The result is

Hi Optional("TextOfTextField")

Okay. So it's a very simple question.

I hope someone can help me.


回答1:


The text of your textField is an optional value because a text field can sometimes be empty. So, use an if let to unwrap the variable and make sure it's not nil — otherwise your program could crash:

if let text: String = textField.text {
   textLabel.text = text
}



回答2:


So the problem here is that the textField's text is an optional, that you have to unwrap for using it.

Just add an ! to textField.text like this:

textLabel.text = "Hi \(textField.text!)"

Your output will now be Hi TextOfTextField


You have a few safer options to unwrap your optionals:

  1. nil coalescing operator: ??
    This will use either textField.text, or, if that's nil, use the other value provided, "?" in this case

    textLabel.text = "Hi \(textField.text ?? "?")"
    
  2. if let statement:
    Note that this will only update your text field's text, if it's not nil. You could provide an else statement to deal with that.

    if let text = textField.text {
        textField.text = "Hi \(text)"
    }
    
  3. guard let statement:
    This works similarly like the if let statement, except that your function will end after the statement.

    guard let text = textField.text else { return }
    textField.text = "Hi \(text)"
    

Hope this helps :)




回答3:


One more way can be to use Guard to check if it is not nil.

guard let nameText = textField.text else {
    print("break if nil")
    return
}
textLabel.text = "Hi \(nameText!)" 

Using guard makes sure your app fails early if the condition fails.




回答4:


In my case for Swift 4.x, I unwrapped by using below command for option Int? values or Optional list cont:

\(topics?.count ?? 0 )



回答5:


It Just a Simple using Swift here you can i just set 1 button and when it's click my textfeild text set into Lable using Swift 3

class ViewController: UIViewController {
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet weak var textField: UITextField!

    @IBAction func updateButton(sender: UIButton) {
        textLabel.text = "Hi \(textField.text!)"
    }



回答6:


I solved this problem with this for Swift 3;

self.label.text = "\(transaction.amount!)"


来源:https://stackoverflow.com/questions/33986284/why-is-optionaltext-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!