问号'是什么意思?迅速地? [英] What the meaning of question mark '?' in swift?

查看:132
本文介绍了问号'是什么意思?迅速地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift编程中,我发现了一些带有对象的问号.

In Swift programming I found some question marks with objects.

var window: UIWindow?

有人可以解释它的用途吗?

Can anybody explain the use of it?

推荐答案

您可以同时使用iflet来处理可能是 丢失的.这些值表示为optionals.一个optional 值包含一个值或包含nil来指示 价值缺失.在值的类型后写一个问号(?) 将该值标记为optional.

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

如果可选值是nil,则条件是false,并且代码在 大括号被跳过.否则,将解压缩可选值,然后 分配给let之后的常量,这使展开的值 在代码块中可用.

If the optional value is nil, the conditional is false and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code.

摘录自:Apple Inc."Swift编程语言". iBooks. https://itun.es/pk/jEUH0.l

Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/pk/jEUH0.l

例如:

var optionalString: String? = "Hello"
optionalString == nil

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

在此代码中,输出将为Hello! John Appleseed.如果将optionalName的值设置为nil. if条件结果将是false,并且if中的代码将被跳过.

In this code, the output would be Hello! John Appleseed. And if we set the value of optionalName as nil. The if conditional result would be false and code inside that if would get skipped.

这篇关于问号'是什么意思?迅速地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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