Swift: Testing optionals for nil

前端 未结 14 655
攒了一身酷
攒了一身酷 2020-12-08 08:51

I\'m using Xcode 6 Beta 4. I have this weird situation where I cannot figure out how to appropriately test for optionals.

If I have an optional xyz, is the correct w

14条回答
  •  爱一瞬间的悲伤
    2020-12-08 09:20

    One option that hasn't specifically been covered is using Swift's ignored value syntax:

    if let _ = xyz {
        // something that should only happen if xyz is not nil
    }
    

    I like this since checking for nil feels out of place in a modern language like Swift. I think the reason it feels out of place is that nil is basically a sentinel value. We've done away with sentinels pretty much everywhere else in modern programming so nil feels like it should go too.

提交回复
热议问题