Optional 补充Using the Nil-Coalescing Operator

摘自:Xcode自带开发文档
Using the Nil-Coalescing Operator
Use the nil-coalescing operator (??) to supply a default value in case the Optional instance is nil. Here a default path is supplied for an image that is missing from imagePaths.

Listing 6

let defaultImagePath = "/images/default.png"
let heartPath = imagePaths["heart"] ?? defaultImagePath
print(heartPath)
// Prints "/images/default.png"

The?? operator also works with another Optional instance on the right-hand side. As a result, you can chain multiple ?? operators together.

Listing 7

let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
print(shapePath)
// Prints "/images/default.png"

TODO:后期翻译待补充

你可能感兴趣的:(Optional 补充Using the Nil-Coalescing Operator)