美文网首页
Optional 补充Using the Nil-Coalesc

Optional 补充Using the Nil-Coalesc

作者: iOS倔强青铜 | 来源:发表于2017-09-20 23:35 被阅读8次

摘自: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-Coalesc

      本文链接:https://www.haomeiwen.com/subject/pjmasxtx.html