Why is Optional(“Text”) - Swift

后端 未结 6 1028
我寻月下人不归
我寻月下人不归 2020-12-11 13:51

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

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 14:38

    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 :)

提交回复
热议问题