为什么是Optional(“Text”) - Swift [英] Why is Optional("Text") - Swift

查看:202
本文介绍了为什么是Optional(“Text”) - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Swift。所以我创建了一个带有标签,按钮和文本字段的简单应用程序。单击该按钮时,应用程序必须使用文本字段的文本更改标签。

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) "
    }

结果是


Hi可选(TextOfTextField )

Hi Optional("TextOfTextField")

好的。所以这是一个非常简单的问题。

Okay. So it's a very simple question.

我希望有人可以帮助我。

I hope someone can help me.

推荐答案

textField的文本 是一个可选值,因为文本字段有时可能是空的。所以,使用如果让打开变量 ,请确保它不是nil - 否则你的程序可能会崩溃:

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
}

这篇关于为什么是Optional(“Text”) - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆