Sobes.tech
Junior

What is wrapped?

sobes.tech AI

Answer from AI

wrapped is the value of an optional type after successfully extracting (unwrapping) its contents. An Optional<<Wrapped>> optional either holds a value of type Wrapped or is nil. Extraction allows access to the Wrapped value if it exists.

Examples of extraction:

  1. Forced unwrapping !:

    var optionalString: String? = "Hello"
    let unwrappedString = optionalString! // Gets the value "Hello"
    // If optionalString == nil, a crash occurs
    
  2. Optional binding if let or guard let:

    var anotherOptionalString: String? = "World"
    if let guaranteedString = anotherOptionalString {
        // Inside this block, guaranteedString is of type String (unwrapped)
        print(guaranteedString)
    }
    
  3. Optional chaining ?:

    class MyClass { var property: String? }
    var instance: MyClass? = MyClass()
    instance?.property = "Value" // If instance is not nil, the property is set
    let retrievedValue = instance?.property // retrievedValue will be String?
    
  4. Nil-coalescing operator ??:

    var yetAnotherOptionalString: String? = nil
    let defaultValue = yetAnotherOptionalString ?? "Default" // defaultValue will be "Default" (String)
    // If yetAnotherOptionalString had a value, it would be used as unwrapped.
    

In the context of Swift, a wrapped value is the actual content that was "inside" the optional before it was unwrapped.

What is wrapped? — iOS - sobes.tech