Optional type is used when the value may be absent. A variable or constant is optional if there is a question mark after the type name. For examplevar index: Int? = nil
Because the value of an optional type may be nil, the compiler does not allow access to its data. For example, the print(index) statement will report an error.
However, we can check its value condition using if. For exampleif index != nil { ... }
We can also check for the condition of the value initialization of another constant where the optional value is assigned to the constant. For exampleif let i = index { print(i) }
If the value of index is nil, the constant initialization fails and returns false, then the statement block in the body of the conditional expression is not executed. Conversely, if the index has a value, that value is rendered
When using vscode, press Ctrl + Shift + B
to compile and press F5
key to run the program.
Can't see mail in Inbox? Check your Spam folder.
Comments
There are currently no comments
New Comment