Optional is a special type in Swift that can either contain a value of type T or contain no value at all (nil). It is written as T?. It allows you to explicitly indicate that a variable may not have a value and guarantees that a check for a value is performed at compile time.
Value unwrapping mechanisms:
let str: String? = "hello" if let s = str { print(s) }
guard let s = str else { return } print(s)
let s = str!
(MAY lead to a runtime crash if the value is nil)
let length = str?.count
??):let value = str ?? "default"
Can you assign nil to a variable of type String, rather than String?, and what will happen?
Answer:
No, you cannot assign a value of nil to a variable of a regular type (String). Only optionals can be nil; otherwise, a compilation error will occur.
Example:
var a: String // a = nil // compilation error: Nil cannot be assigned to type 'String' var b: String? b = nil // OK
Story
In the application, a force unwrapping of values was done, assuming that a valid response would always come from the database; a crash occurred when the field was absent. The error was resolved by adding an additional check using optional binding.
Story
When sending push notifications, the username was stored in a non-optional variable, which led to the application crashing when an empty name came from the API. After analysis, the type was changed to optional, and nil handling was added.
Story
In a project, when passing an optional value to a function, the argument was declared without the optional type. Hidden bugs and crashes arose. Changes were made: the parameter type became optional, and checks for the presence of a value were added.