Why would I use if and let together, instead of just checking if the original variable is nil? (Swift)

In “The Swift Programming Language.” book, Apple mentions using if and let together when accessing an optional variable.

The book gives the following code for example:

  • Cannot load underlying module for 'RealmSwift'
  • Convert Character to Int in Swift
  • How to access the content of a custom cell in swift using button tag?
  • Firebase query sort order in swift?
  • Resize inputAccessoryView dynamically in iOS 8
  • Selector with completion, 2 variables and time interval
  • var optionalString: String? = "Hello"
    optionalString == nil
    
    var optionalName: String? = "John Appleseed"
    var greeting = "Hello!"
    if let name = optionalName {
        greeting = "Hello, \(name)"
    }
    

    What is the advantage of using if let name = optionalName, rather than if optionalName != nil (and always referring to it as, optionalName)? Is there any difference, or is it simply convention?

    2 Solutions Collect From Internet About “Why would I use if and let together, instead of just checking if the original variable is nil? (Swift)”

    Because it also unwraps the optional value, so this code:

    if let name = optionalName {
        greeting = "Hello, \(name)"
    }
    

    is equivalent to:

    if optionalName != nil {
        let name:String = optionalName!
        greeting = "Hello, \(name)"
    }
    

    This language sugar is known as Optional Binding in Swift.

    Optional Types

    In Swift T and T? are not the same types, but the underlying value of an optional T? type can easily be realized by using the ! postfix operator, e.g:

    let name:String = optionalName!
    

    Which now can be used where a String is expected, e.g:

    func greet(name:String) -> String {
        return "Hello, \(name)"
    }
    
    greet(name)
    

    Although as its safe to do so, Swift does let you implicitly cast to an optional type:

    let name = "World"
    let optionalName: String? = name
    
    func greet(optionalName:String?) -> String? {
        if optionalName != nil {
            return "Hello, \(optionalName)"
        }
        return nil
    }
    
    //Can call with either String or String?
    greet(optionalName)
    greet(name)
    

    It isn’t actually needed in that case. You could just use optionalName in the if. But if optionalName was a calculated property it would have to be calculated in the conditional then again in the body. Assigning it to name just makes sure it is only calculated once.