What makes Swift's “Optional” safer than Objective-C's “nil”?

佐手、 提交于 2019-12-06 18:39:04

问题


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.

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


回答1:


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.

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 = ...
}

Now I can simply do it as

 obj?.property = ...

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




回答2:


In general, in programming we want to avoid variables that have no value (null or nil) because using them often results in undefined behaviour (exceptions, errors, crashes).

For example, it is a common practice for Array references to be set to empty arrays instead of nil. On an empty array we can use all the Array methods, e.g. indexOf or count. Using them on nil would result in a crash.

Optionals allow us to specify that some variables are never empty, therefore we can use them safely and the compiler checks that nil is never assigned to them. Also, the compiler enforces that every conversion from optionals to non-optionals is explicit (we are always checking for nil when needed).

So the answer would be that optionals:

  1. Enforce good programming practices.
  2. Allow for better code checking at compilation time

Thus preventing programming errors.

Also note that the you should always try to avoid optionals when possible. The greatest power of optionals is the fact that most variables are not optionals.




回答3:


It becomes "safe" because it forces the programmer to write more explicit code.

  • The if let ... and guard syntax explicitly says "do this only if there are values for these variables".
  • The ! syntax makes the program crash if the variable is nil when the programmer did not expect it to be nil.

In contrast, Objective-C's way of making calls to nil a no-op may let the program continue to execute until such point that nil is not acceptable. One common example is nil NSString variables. Many API calls are happy with a nil NSString except when constructing NSAttributedString (it won't accept a nil NSString parameter and crashed your app). Hence when you get an NSString variable unexpectedly becomes nil, it may be a while later until your app crashes because it tries to construct an attributed string with that nil value.

For a more complete illustration on the problem that Optionals tried to solve, consider this post back from 2010 by Daniel Jalkut. This was written long before Swift.




回答4:


In Objective-C, you can define a variable without a value. If you want to use that variable before assigning a value, you will get a undefined behaviour(which is very bad). On contrary, swift prevents the scenario where the value of a object is unknown.



来源:https://stackoverflow.com/questions/35546224/what-makes-swifts-optional-safer-than-objective-cs-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!