The !
mark is used for the optional value in Swift to extract the wrapped value of it, but the value can be extracted without the !
:
var optionalString: String? = "optionalString"
println(optionalString)
another example using the !
:
var optionalString: String? = "optionalString"
println(optionalString!)
both the codes above get the right value, so I wonder what's the difference between using and not using !
, is it just for detect an error at runtime if the optional value is nil or something else? Thanks in advance.
I've never heard of Swift before now, but reading the documentation seems clear
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 benil
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.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:
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.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,
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":