lysov lysov - 4 months ago 6x
Swift Question

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

In the following lines of code, the

constant implicitly inherits from the right side the
type instead of the

var variable: String? = "hello"

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


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.