开发语言 ios 【Swift 60秒】92 - Nil coalescing - 0x01 我的小作品

📅 2026-11-30 👤 拼多多助力营销技巧 📂 pdd助力 👁️ 497 次阅读

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 搜索即可~ 拼多多帮助力入口

参考文章

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧