是什么使Swift的“可选"功能变得如此强大?比Objective-C的“零"安全吗? [英] What makes Swift's "Optional" safer than Objective-C's "nil"?

查看:64
本文介绍了是什么使Swift的“可选"功能变得如此强大?比Objective-C的“零"安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple似乎声称 Swift中的Optional类型比nil在Objective-C中,但我不明白为什么会这样.

Apple seems to claim that the Optional type in Swift is safer than nil in Objective-C, but I don't understand why this is so.

在实现上比nil更安全的显着区别是什么?这将如何影响我的代码?

What are the salient differences in implementation that make Optionals safer than nil, and how will this affect my code?

推荐答案

在使用变量以避免问题之前,我总是检查变量是否为nil.但是,仍然偶尔会出现一个值,可能会以nil的形式出现,令我惊讶的是,或者有时我只是忘了检查.

I always do check if a variable is nil before I use it to avoid problems. However, it still happens once in a while that a value might come in as nil, to my surprise -- or sometimes I just plain forget to check.

在Swift中编写越来越多的代码后,我发现使用可选变量确实为避免忽略对nil值的检查提供了很多便利.我真的不记得由于nil变量访问而导致的任何崩溃(除非我强制解开某些变量;因此,除非您知道自己在做什么,否则不要强行解开).

After I code more and more in Swift, I have found that using optional variables indeed provides a lot of convenience to avoid ignoring the checking for nil values. I don't really recall any crashes due to nil variable access (unless I force the unwrapping of some variable; so don't do force unwrapping unless you know what you are doing).

此外,我以前在很多地方都写过很多这样的代码:

Besides, I used to write a lot of code like this in many places:

if (obj != nil) {
    obj.property = ...
}

现在我可以简单地做到

 obj?.property = ...

代码现在看起来干净利索.你也不喜欢吗?

The code now looks clean and sharp. Don't you like it too?

这篇关于是什么使Swift的“可选"功能变得如此强大?比Objective-C的“零"安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆