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:
-
Forced unwrapping
!:var optionalString: String? = "Hello" let unwrappedString = optionalString! // Gets the value "Hello" // If optionalString == nil, a crash occurs -
Optional binding
if letorguard let:var anotherOptionalString: String? = "World" if let guaranteedString = anotherOptionalString { // Inside this block, guaranteedString is of type String (unwrapped) print(guaranteedString) } -
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? -
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.