问号'是什么意思?迅速地? [英] What the meaning of question mark '?' in swift?
问题描述
在Swift编程中,我发现了一些带有对象的问号.
In Swift programming I found some question marks with objects.
var window: UIWindow?
有人可以解释它的用途吗?
Can anybody explain the use of it?
推荐答案
您可以同时使用
if
和let
来处理可能是 丢失的.这些值表示为optionals
.一个optional
值包含一个值或包含nil
来指示 价值缺失.在值的类型后写一个问号(?) 将该值标记为optional
.
You can use
if
andlet
together to work with values that might be missing. These values are represented asoptionals
. Anoptional
value either contains a value or containsnil
to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value asoptional
.
如果可选值是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屋!