1

I'm a little confused about Swift Wrap and Unwrap! So lets say this is my code:

var name:String? = "FirstName"
print(name)

Does the print function automatically unwrap the name which is optional? so I do not need to say print(name!) in order to unwrap the name? I guess what I am trying to understand is these two are equivalent for unwraping an optional variable?

print("name") is just like saying print ("name"!)

The other question I have is about nil. is saying var name:String? = "FirstName" equivalent to saying var name:String? = nil . So does assigning a nil value wraps a variable?

user3314399
  • 317
  • 4
  • 9
  • 23
  • Possible duplicate of [No need to unwrap optionals in Swift?](http://stackoverflow.com/questions/24040362/no-need-to-unwrap-optionals-in-swift) –  Jan 26 '16 at 02:18
  • 4
    Have you tried these things out in playground? It's great for finding things out like this. That being said, no. `print()` doesn't unwrap things because if you try it out in playground it will print out `optional("FirstName")` – Eendje Jan 26 '16 at 02:18

1 Answers1

9

When something can be nil it can be two things, it can be Some (the value of the given type) or it can be nil.

declaring something like this:

var name: String?

Means that the name variable can be nil, if you assigned a value to it you need to unwrap it to use it.

name = "FirstName"

Now the name variable has been defined, however you still need to ensure it's not nil in some cases, in other cases however (such as when the string doesn't need to be not nil) optional chaining is used.

Optional chaining allows the continuous evaluation of nil or some throughout a statement as long as it's not required to be not nil. If that is the case then you will need to unwrap it:

let someThingRequiresAString = NeedAStringInitializer(string: name!)

In the above statement if name is nil the program will crash, there are several approaches to dealing with things like this, here's a quick example:

if name != nil {

let someThingRequiresAString = NeedAStringInitializers(string: name!)
}

Here you know you can do this b/c name has been evaluated to not be nil. You can also use a nil coalescing operator, or a guard statement. Here's a quick example of nil coalescence in Swift:

let someThingRequiresAString = NeedAStringInit(string: name ?? "New Name")

The optional paradigm is quite powerful and expressive.

Fred Faust
  • 6,696
  • 4
  • 32
  • 55