lysov lysov - 5 months ago 8
Swift Question

Why the constant inherits the "String?" type instead of the "String?"

In the following lines of code, the

anotherVariable
constant implicitly inherits from the right side the
String
type instead of the
String?


var variable: String? = "hello"

if let anotherVariable = variable { // Unwrapping
// "anotherVariable" constant has a String type and its value is "hello"
}

Answer

Yes, this is optional unwrapping. When you use if let on an optional value:

  1. You only enter the body of the condition if the optional value is non-nil, and
  2. The value that you assign it to will be of a non-optional type, so you can use it without unwrapping within the scope of the body of the conditional.
Comments