Wrong example code in documentation for Swift optionals -> optional chaining

Originator:davidmarmoy
Number:rdar://39750241 Date Originated:
Status: Resolved:
Product:Swift documentation Product Version:
Classification: Reproducible:Always
 
Summary: The code example for optional chaining in the Swift optional documentation https://developer.apple.com/documentation/swift/optional has a mistake, printing the wrong conclusion.

The example writes the following: 

    if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
        print("The star image is in PNG format")
    }
    // Prints "The star image is in PNG format"

The code above however cannot state anything about the format of the path, only whether the path is nil or not.

Steps to Reproduce:
Put the following code in a Playground project:

    var imagePaths = ["star": "star"]

    if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
        print("The star image is in PNG format")
    }

Expected Results:
Don't print anything, since the path does not have the .png suffix

Actual Results:
Prints "The star image is in PNG format"


Notes: To correct the code you could add ", isPNG" to the condition, like this:

    if let isPNG = imagePaths["star"]?.hasSuffix(".png"), isPNG {
        print("The star image is in PNG format")
    }

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!