?? Swift中的运算符 [英] ?? operator in Swift
问题描述
在"Swift编程语言"一书(第599页)中,我遇到了使我感到困惑的这段代码.它是这样的:
In the "The Swift Programming Language" book (page 599), I came across this code snippet that kind of confused me. It went like this:
func buyFavoriteSnack(person:String) throws {
let snackName = favoriteSnacks[person] ?? "Candy Bar"
try vend(itemName:snackName)
}
它的解释是:
buyFavoriteSnack(_ :)函数查找给定人的最爱小吃,并尝试为他们购买.如果他们没有列出最喜欢的小吃,它会尝试购买糖果.如果他们...
The buyFavoriteSnack(_:) function looks up the given person's favorite snack and tries to buy it for them. 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?
推荐答案
它是零合并运算符"(也称为默认运算符").除非a
是nil
,否则a ?? b
是a
的值(即a!
),在这种情况下,它会产生b
. IE.如果缺少favouriteSnacks[person]
,则代之以赋值"Candy Bar"
.
It is "nil coalescing operator" (also called "default operator"). a ?? b
is value of a
(i.e. a!
), unless a
is nil
, in which case it yields b
. I.e. if favouriteSnacks[person]
is missing, return assign "Candy Bar"
in its stead.
编辑 从技术上讲,可以解释为:(摘自下面的Badar Al-Rasheed的回答)
EDIT Technically can be interpreted as: (From Badar Al-Rasheed's Answer below)
let something = a != nil ? a! : b
这篇关于?? Swift中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!