Is the optional Swift chain always executed with the if let construct, or is this done using the question mark with the option?

According to Apple docs, an optional chain:

You specify an optional chain by placing a question mark (?) After the optional value by which you want to call a property, method, or index if the optional parameter is not zero .... the optional chain gracefully fails when the optional parameter is zero .. .

My interpretation of this is that a construct like this is an optional chain:

someMasterObject.possiblyNilHandler?.handleTheSituation()

... and that the above line will call the handleTheSituation method if the handler is not nil, and with an error (the line is skipped) if the handler is zero.

However, almost all the examples that I see in the optional chain use the "if let" construct, according to:

if let handler = someMasterObject.possiblyNilHandler{
  handler.handleTheSituation()
}

In fact, the documentation and examples I found on the net use the "if let" construct so much in connection with an optional chain that it seems like it's an optional chain.

However, I proceed from the assumption that my first example is the supported use of an optional chain, and if the if let construct is another construct using (or being closely related to) an optional chain?
+4
source share
3 answers

- let , . if-body if- , nil. ( .)

let , ( ). , someMasterObject /nil, , "" - let.

( ) "", : . , , .


, someMasterObject nil, , , let. , , "nil on failure":

if let handler = someMasterObject?.possiblyNilHandler{
  return handler.handleTheSituation()
} else {
  return FAILED_TO_CALL
}

, nil , nil handleTheSituation!

return someMasterObject?.possiblyNilHandler?.handleTheSituation()

, , if-let:

result_of_expression = someMasterObject?.possiblyNilHandle?.handleTheSituation()

if let master = someMasterObject {
   if let handler = master.possiblyNilHandler {
       result_of_expression = handler.handleTheSituation()
   } else {
       result_of_expression = nil
   }
} else {
   result_of_expression = nil
}
+5

, (if let):

person?.name = "Fred"              // assign "Fred" to name property if person is not nil

person?.congratulate()             // call congratulate method if person is not nil

let name = person?.name ?? "none"  // nil coalescing operator

let age = dict?["age"] ?? 0        // subscripting an optional variable

if var name = person?.name {       // optional binding using var instead of let
+10

- - if. nil, . , .

if , , :

func printNumberOfRooms() {
    println("The number of rooms is \(numberOfRooms)")
}

if john.residence?.printNumberOfRooms() != nil {
    println("It was possible to print the number of rooms.")
} else {
    println("It was not possible to print the number of rooms.")
}

.

, nil , . , Void?, Void, .

+2

Source: https://habr.com/ru/post/1569644/


All Articles