ptt
ptt

Reputation: 123

What is to unwrap a variable?

I have been trying to get my head around the concept of optionals and implicitly unwrapped optional but I just don't get the terminology? My questions are:

  1. What is wrapped in programming? What would a wrapped String be?
  2. What is unwrapping?
  3. What is the difference between an Optional (?) and a implicitly unwrapped functional (!)
  4. When do you use ? or !
  5. What do they mean with implicitly in the term implicitly unwrapped optional?

Is unwrapping just revealing a variable's true value whether it is nil or a value?

Upvotes: 4

Views: 4792

Answers (1)

Khiem Tran
Khiem Tran

Reputation: 6169

1.Wrapped mean that you put the value in a variable, which maybe empty. For example:

let message: String? // message can be nil
message = "Hello World!" // the value "Hello World!" is wrapped inside the message variable.

print(message)  // print the value that is wrapped in message - it can be null.

2.Unwrap means you get the value of the variable to use it.

textField?.text = "Hello World!" // you get the value of text field and set text to "Hello World!" if textField is not nil.
textField!.text = "Hello World!" // force unwrap the value of text field and set text to "Hello World!" if text field is not nil, other wise, the application will crash. (you want to make sure that textField muse exists).

3.Optional: is a variable that can be nil. When you use its value you need to unwrap it explicitly:

let textField: UITextField? // this is optional
textField?.text = "Hello World" // explicitly tells the compiler to unwrap it by putting an "?" here
textField!.text = "Hello World" // explicitly tells the compiler to unwrap it by putting in "!" here.

Implicitly unwrap optional(?) is an optional (value can be nil). But when you use it you don't have to tells the compiler to unwrap it. It will be forced unwrapped implicitly (default)

let textField: UITextField!
textField.text = "Hello World!" // it will forced unwrap the variable and the program will crash if the textField is nil.

4.Try to always use optional(?) in most case if you think the value can be nil. Use implicitly unwrapped optional(!) only when you are 100% sure that the variable can't be nil at the time you use it (but you can't set it in Class constructor).

5.Implicitly means automatically, you don't have to tell the compiler, it will do it automatically, and it's bad because sometime you don't know that you are unwrapping an optional that may cause the program crash. In programming, explicit always better that implicit.

Upvotes: 6

Related Questions