Optional type in Swift


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 example

var 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 example

if 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 example

if 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.

Currently unrated


There are currently no comments

New Comment


required (not published)



What is 1 × 4?