Swift Optionals
Swift's Optional type is used to handle the absence of a value. Optionals say "there is a value, and it equals x" or "there isn't a value at all".\n\nSwift language defines postfix ? as a shorthand for the named type Optional, in other words, the following two declarations are equal:\n\nvar optionalInteger: Int?var optionalInteger: Optional\nIn both cases, the variable optionalInteger is an optional integer type. Note that there is no space between the type and **?**.\n\nOptional is an enum with two cases, None and Some(T), used to represent a value that may or may not exist. Any type can be explicitly declared as (or implicitly converted to) an optional type. When declaring an optional type, make sure to use parentheses to give the ? operator an appropriate scope. For example, to declare an optional array of integers, it should be written as (Int[])?; writing Int[]? will result in an error.\n\nWhen you declare an optional variable or optional property without providing an initial value, its value will default to nil.\n\nOptionals follow the LogicValue protocol, so they can appear in boolean contexts. In this case, if the optional type T? contains any value of type T (meaning its value is Optional.Some(T)), this optional type equals true, otherwise it equals false.\n\nIf an instance of an optional type contains a value, you can use the postfix operator ! to access that value, as shown below:\n\noptionalInteger = 42 optionalInteger! // 42\nUsing the ! operator to access an optional variable with a value of nil will result in a runtime error.\n\nYou can use optional chaining and optional binding to selectively perform operations on optional expressions. If the value is nil, no operations will be executed, and there will be no runtime error.\n\nLet's look at the following example in detail to understand the application of optional types in Swift:\n\nimport Cocoavar myString:String? = nilif myString != nil { print(myString)}else{ print("String is nil")}\nThe output of the above program is:\n\nString is nil\nOptional types are similar to the nil value of pointers in Objective-C, but nil is only useful for classes (class), whereas optional types are available for all types and are safer.\n\n* * *\n\n## Forced Unwrapping\n\nWhen you are sure that an optional type does contain a value, you can add an exclamation mark (!) after the optional's name to get its value. This exclamation mark means "I know this optional has a value, please use it." This is known as forced unwrapping of optional values.\n\nAn example is as follows:\n\nimport Cocoavar myString:String? myString = "Hello, Swift!"if myString != nil { print(myString)}else{ print("myString Value is nil")}\nThe output of the above program is:\n\nOptional("Hello, Swift!")\nTo force unwrap the optional value, use an exclamation mark (!):\n\nimport Cocoavar myString:String? myString = "Hello, Swift!"if myString != nil { // Forced Unwrapping print( myString! )}else{ print("myString Value is nil")}\nThe output of the above program is:\n\nHello, Swift!\n> Note:\n> \n> Using `!` to access a non-existent optional value will result in a runtime error. Before using `!` to force unwrap a value, always make sure the optional contains a non-`nil` value.\n\n* * *\n\n## Automatic Unwrapping\n\nYou can use an exclamation mark (!) instead of a question mark (?) when declaring an optional variable. This way, the optional variable does not need to have an exclamation mark (!) added when accessing its value; it will be automatically unwrapped.\n\nAn example is as follows:\n\nimport Cocoavar myString:String! myString = "Hello, Swift!"if myString != nil { print(myString)}else{ print("myString Value is nil")}\nThe output of the above program is:\n\nHello, Swift!\n\n* * *\n\n## Optional Binding\n\nUse optional binding to determine whether an optional type contains a value, and if it does, assign that value to a temporary constant or variable. Optional binding can be used in if and while statements to evaluate an optional type's value and assign it to a constant or variable.\n\nWrite an optional binding in an if statement like this:\n\nif let constantName = someOptional { statements }\nLet's look at a simple example of optional binding:\n\nimport Cocoavar myString:String? myString = "Hello, Swift!"if let yourString = myString { print("Your string value is - \\(yourString)")}else{ print("Your string has no value")}\nThe output of the above program is:\n\nYour string value is - Hello, Swift!
YouTip