当前位置: 首页 > news >正文

【Swift 60秒】92 - Nil coalescing

0x00 Lesson

The nil coalescing operator unwraps an optional and returns the value inside if there is one. If there isn’t a value - if the optional was nil - then a default value is used instead. Either way, the result won’t be optional: it will either by the value from inside the optional or the default value used as a back up.

Here’s a function that accepts an integer as its only parameter and returns an optional string:

func username(for id: Int) -> {if id == 1 {return "Taylor Swift"} else {return nil}
}

If we call that with ID 15 we’ll get back nil because the user isn’t recognized, but with nil coalescing we can provide a default value of “Anonymous” like this:

let user = username(for: 15) ?? "Anonymous"

That will check the result that comes back from the username() function: if it’s a string then it will be unwrapped and placed into user, but if it has nil inside then “Anonymous” will be used instead.


0x01 我的小作品

欢迎体验我的作品之一:小五笔
五笔学习好帮手
App Store 搜索即可~


http://www.lryc.cn/news/4548.html

相关文章:

  • python pip安装的包的路径
  • 个人收藏学习
  • 【C++】类和对象---需掌握的功能
  • 2.12、进程互斥的软件实现方法
  • Java面试题-数据库
  • select 与 where、group by、order by、limit 子句执行优先级比较
  • 【Docker】用开源umami监控你的站点访问量
  • java环境配置
  • Linux系统服务:Apache安装及配置应用
  • 动态规划(Dynamic Programming)——背包问题
  • JVM学习02:内存结构
  • 6年软件测试经验,从我自己的角度理解自动化测试
  • 三种方式查看linux终端terminal是否可以访问外网ping,curl,wget
  • 【Call for papers】SIGCOMM-2023(CCF-A/计算机网络/2023年2月15日截稿)
  • Chapter5:机器人感知
  • [acwing周赛复盘] 第 90 场周赛20230211 补
  • 数组
  • MicroBlaze系列教程(4):AXI_UARTLITE的使用
  • GO 中的 init 函数
  • 使用C#编写k8s CRD Controller
  • Ansible---playbook剧本
  • Delphi 中TImageCollection和TVirtualImageList 控件实现high-DPI
  • Ros中如何给UR5配置自定义工具 | 在Rviz中给UR5机器人装载定义工具 | UR5配置自定义末端执行器
  • 数据库 delete 表数据后,磁盘空间为什么还是被一直占用?
  • docker-微服务篇
  • 图像优化篇
  • 在surface go 2上安装ubuntu 20.04
  • Java:SpringMVC的使用(1)
  • 自动化测试岗位求职简历编写规范+注意事项,让你的简历脱颖而出
  • C 字符串