What the difference between using or not using “!” in Swift?

牧云@^-^@ 提交于 2019-12-04 16:40:41

As others have already stated, a really good place to start would be with the official documentation. This topic is extraordinarily well covered by the documentation.

From the official documentation:

Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

println() is probably not the best way to test how the ! operator works. Without it, println() will either print the value or nil, with it it will either print the value or crash.

The main difference is when we're trying to assign our optional to another value or use it in an argument to a function.

Assume optionalValue is an optional integer.

let actualValue = optionalValue

Using this assignment, actualValue is now simply another optional integer. We haven't unwrapped the value at all. We have an optional rather than an integer.

Meanwhile,

let actualValue = optionalValue!

Now we're forcing the unwrap. Actual value will be an integer rather than an optional integer. However, this code will cause a runtime exception is optionalValue is nil.

Your question is answered in the book "The Swift Programming Language: iBooks

Download it and search it for "!".

You could've easily found the answer without having to ask here. For future reference, please always remember to look in the manual first.

From "The Swift Programming Language":

You can use an "if" statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to "true"; if it has no value at all, it evaluates to "false".

Once you're sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional's name. The exclamation mark effectively says, "I know that this optional definitely has a value; please use it." This is known as forced unwrapping of the optional's value.

I've never heard of Swift before now, but reading the documentation seems clear

"Using the ! operator to unwrap an optional that has a value of nil results in a runtime error."

If in your application nil is a valid and expected value in any normal circumstance and/or you want to trap and handle it in your code then I suggest that you don't use it. If you never expect it to be nil then use it as a debug aid. Runtime error suggest to me that your program will be terminated with a message reported by the OS.

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