Why is Optional(“Text”) - Swift

后端 未结 6 1011
我寻月下人不归
我寻月下人不归 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:43

    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
    }
    

提交回复
热议问题