[英]?? operator in Swift
In the "The Swift Programming Language" book (page 599), I came across this code snippet that kind of confused me. 在“The Swift Programming Language”一书(第599页)中,我遇到了这段令我困惑的代码片段。 It went like this:
它是这样的:
func buyFavoriteSnack(person:String) throws {
let snackName = favoriteSnacks[person] ?? "Candy Bar"
try vend(itemName:snackName)
}
Its explanation was: 它的解释是:
The buyFavoriteSnack(_:) function looks up the given person's favorite snack and tries to buy it for them.
buyFavoriteSnack(_ :)函数查找给定人最喜欢的零食,并尝试为他们购买。 If they don't have a favorite snack listed, it tries to buy a candy bar.
如果他们没有列出最喜欢的零食,它会尝试买一个糖果棒。 If they...
如果他们...
How can this explanation map to the "??" 这个解释如何映射到“??” operator in the code given.
给定代码中的运算符。 When should/can we use this syntax in our own code?
什么时候应该/我们可以在自己的代码中使用这种语法吗?
It is "nil coalescing operator" (also called "default operator"). 它是“nil coalescing operator”(也称为“默认运算符”)。
a ?? b
a ?? b
is value of a
(ie a!
), unless a
is nil
, in which case it yields b
. a ?? b
是值a
(即a!
),除非a
是nil
,在这种情况下,它产生b
。 Ie if favouriteSnacks[person]
is missing, return assign "Candy Bar"
in its stead. 即如果
favouriteSnacks[person]
失踪,则返回指定"Candy Bar"
。
EDIT Technically can be interpreted as: (From Badar Al-Rasheed's Answer below) 编辑技术上可以解释为:(来自下面的Badar Al-Rasheed的答案)
let something = a != nil ? a! : b
let something = a ?? b
手段
let something = a != nil ? a! : b
This: 这个:
let snackName = favoriteSnacks[person] ?? "Candy Bar"
Is equals this: 等于这个:
if favoriteSnacks[person] != nil {
let snackName = favoriteSnacks[person]
} else {
let snackName = "Candy Bar"
}
Explaining in words, if the let
statement fail to grab person
from favoriteSnacks
it will assigned Candy Bar to the snackName
用文字解释,如果
let
语句无法从favoriteSnacks
获取person
,它会将Candy Bar分配给snackName
The nil-coalescing operator a ?? b
零合并算子
a ?? b
a ?? b
is a shortcut for a != nil ? a! : b
a ?? b
是a != nil ? a! : b
的快捷方式a != nil ? a! : b
a != nil ? a! : b
One addition to @Icaro's answer you can declare values without initialize them. @ Icaro回答的一个补充是你可以在不初始化它们的情况下声明值。 In my opinion this is better:
在我看来这更好:
func buyFavoriteSnack(person:String) throws {
// let snackName = favoriteSnacks[person] ?? "Candy Bar"
let snackName: String
if let favoriteSnackName = favoriteSnacks[person] {
snackName = favoriteSnackName
} else {
snackName = "Candy Bar"
}
try vend(itemName:snackName)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.