swiftoptional-variables

What the difference between using or not using "!" in Swift?


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.


Solution

  • 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.