什么是解包变量?

Pab*_*blo 4 swift

我一直试图理解选项的概念并隐式解包可选但我只是没有得到术语?我的问题是:

  1. 什么是编程包装?包裹的字符串是什么?
  2. 什么是解缠?
  3. 可选(?)和隐式解包功能(!)之间有什么区别
  4. 你什么时候用?要么 !
  5. 它们隐含地隐含在未包装的可选项中是什么意思?

解包只是揭示变量的真值,无论它是零还是值?

Dan*_*ran 6

1.Wrapped意味着您将值放在变量中,该变量可能为空.例如:

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.
Run Code Online (Sandbox Code Playgroud)

2.Unwrap意味着你获得变量的值来使用它.

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).
Run Code Online (Sandbox Code Playgroud)

3.Optional:是一个可以为零的变量.当您使用其值时,您需要显式展开它:

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.
Run Code Online (Sandbox Code Playgroud)

隐式解包可选(?)是可选的(值可以是nil).但是当你使用它时,你不必告诉编译器打开它.它将被隐式强制解包(默认)

let textField: UITextField!
textField.text = "Hello World!" // it will forced unwrap the variable and the program will crash if the textField is nil.
Run Code Online (Sandbox Code Playgroud)

4.如果您认为值可以为零,请尝试在大多数情况下始终使用可选(?).仅当您在使用它时100%确定变量不能为零时才使用隐式展开的可选(!)(但您无法在类构造函数中设置它).

5.明确意味着自动,你不必告诉编译器,它会自动执行,而且它很糟糕,因为有时候你不知道你正在打开一个可能导致程序崩溃的可选项.在编程中,显式总是更好的隐含.