Swift String Interpolation显示可选? [英] Swift String Interpolation displaying optional?

查看:70
本文介绍了Swift String Interpolation显示可选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用以下代码并使nameTextField为"Jeffrey"(或其他任何名称)时

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显示...您好,可选("Jeffrey")

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

}

代码按预期工作,并显示nameLabel....您好,杰弗里

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.

推荐答案

必须解开可选项.您必须检查它或像您一样强行拆开包装.想象一下将可选值作为放置值的方框.在访问它之前,需要将其放入.

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

这篇关于Swift String Interpolation显示可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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