Wrapped vs Unwrapped Optionals

I get that a wrapped optional is more secure in that you can't just modify the data contained inside without unwrapping it, but, is there any benefit outside of that to using a wrapped optional as opposed to just using an unwrapped optional. From my perspective at the minute doing

var name:String = ""

vs

var name:String!

is creating two variables, both of which can be modified in pretty much the same way, but

var name:String?

Seems to be just adding a extra step only to have to unwrap it to change it at a later date.

Also, I am new to learning swift.

So, what reason would you choose to use a wrapped optional over an unwrapped optional

Replies

First of all, there's no Unwrapped Optionals.
Normal Optional is not Wrapped Optional, it is not-Implicitly-Unwrapped Optional.

In your example, var name:String! declares Implicitly Unwrapped Optional. You should never omit the word Implicitly.

both of which can be modified in pretty much the same way

Is that true? Please check the following example:
Code Block
var strNonOptional: String = ""
var strImplicitlyUnwrappedOptional: String!
strNonOptional += "abc" //<- Works without problem
strImplicitlyUnwrappedOptional += "abc" //<- Cause your app crash


Non-Optional String and Implicitly Unwrapped Optional String!work differently and using Implicitly Unwrapped Optional can easily leads your app crash.

Do you really want to use such a risky thing just for one extra step?

You use Optional (including Implicitly Unwrapped Optional) when you need to specify that the variable can be in a state there is no valid value.

Using normal Optional, Swift compiler tells you such risky operation.
Code Block
var strOptional: String?
strOptional += "abc" // Value of optional type 'String?' must be unwrapped to a value of type 'String'


In many other languages having nil or null-like things, errors caused by null reference are very common which are caused by a slight mistake even an experienced programmer would fail.

Swift Optional is meant to prevent such easy mistakes by forcing us an extra step, for safety.