You can use the optional option when the value may have a default condition. This means: There is a value that can be equal to the specific value of an X, or it may not have a value.
Note: There is no such concept as an optional value in C or objective-c. In objective-c there is a function that is similar to the option, which returns a nil or returns an object, nil means the default value of a valid object. However, an option can be used only for objects, not for structs, for base c types, or for enumeration values. For these types, the OBJECTIVE-C function typically returns a specific value (such as Nsnotfound) to describe a default value. We can assume that the caller of the function knows that the function has a special value and remembers the checksum by means of the reverse test method. The SWIFT option allows you to specify a default value at any time and does not require a specific constant. Here is an example of the scope where the default value is used.
The string type in Swift has a function called ToInt, which can turn a string into an integer (Int) value. Then, not all strings can be converted to an integer, such as the string "123" can be converted to an integer 123, but the string "Hello", "world" cannot be converted to a definite value.
The following example demonstrates the function ToInt attempts to convert a string to an integer:
Let possiblenumber= "123"
Let Convertednumber=possiblenumber.toint ()
The type of convertednumber is automatically inferred as an option for shaping, Int?
Because the ToInt function may fail to convert, it is better to return an int than to add an optional int?. Integer type optional writing int?, not int. The question mark indicates that the value may be optional, which means that the value can sometimes be an int value, and sometimes there may not be any value. (it cannot contain any other value, such as a bool value or string string, which is either an integer or Nothing).
Nil
You can set the state of the value of an optional variable by a special value of nil:
var serverresponsecode:int? = 404
The serverresponsecode contains a true int value of 404
Serverresponsecode = Nil
Serverresponsecode now does not contain any values.
Note: Nil cannot be used for constants and variables that are not available for selection. If a constant or variable requires a default value under certain conditions, then it needs to be defined as an optional value of the appropriate type.
If you define an optional constant or variable without providing a default value, the value of this constant or variable is automatically set to nil:
var surveyanswer:string? The value of Suveyanswer is automatically set to nil
Note: Nil in Swift is not the same as Objective-c's nil. Nil in objective-c points to a nonexistent object, and nil in Swift does not point to a default value that determines the type. Any type of optional value can be set to nil, not just the object type.
Swift's optional options