Swift 3.0 Optional Chaining

p0lAris

I am new to swift so this is definitely a newbie level question. I was pondering on some Swift 3.0 documentation where I noticed a potential error. I am wondering if the example is incorrect (or ambiguous) or I am in fact missing out on some guideline.

See http://swiftdoc.org/v3.0/type/Optional/ the section about Optional Chaining.

OPTIONAL CHAINING

To safely access the properties and methods of a wrapped instance, use the postfix optional chaining operator (?). The following example uses optional chaining to access the hasSuffix(_:) method on a String? instance.

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

AFAIU, imagePaths["star"]?.hasSuffix(".png") is only supposed to safely unwrap imagePaths and run hasSuffix() only if imagePaths["star"] results in Optional.some(wrapped). This implies that isPNG will be either true or false. Therefore, the implication of the above sample is incorrect where it implicitly claims that if this safely unwraps, then the value is always true.

Here are some examples to explain what I am talking about:

if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
    print("The star has png format")
} else {
    print("The star does not have png format")
}

if let isPNG = imagePaths["portrait"]?.hasSuffix(".png") {
    print("The portrait has png format")
} else {
    print("The portrait does not have png format")
}
// "The portrait has png format\n"

if let isPNG = imagePaths["alpha"]?.hasSuffix(".png") {
    print("The alpha has png format")
} else {
    print("The alpha does not have png format")
}
// "The alpha does not have png format\n"

I am simply wondering if my current analysis is wrong or if SwiftDoc.org needs to change this particular example.

Martin R

Your analysis is correct, and the example at SwiftDoc.org is at least misleading, as the following code demonstrates:

let imagePaths = ["star": "image1.tiff"]

if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
    print("The star has png format")
} else {
    print("The star does not have png format")
}

// Output: The star has png format

The optional binding succeeds if

imagePaths["star"]?.hasSuffix(".png")

is not nil, and that is if the optional chaining could be executed, i.e. if imagePaths["star"] != nil.

A correct way to test for all situations would be

if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
    if isPNG {
        print("The star has png format")
    } else {
        print("The star does not have png format")
    }
} else {
    print("No path in dictionary")
}

Of course this can be simplified in various ways (nil-coalescing operators, pattern matching, ...). For example

switch(imagePaths["star"]?.hasSuffix(".png")) {
case true?:
    print("The star has png format")
case false?:
    print("The star does not have png format")
case nil:
    print("No path in dictionary")
}

or

let isPNG = imagePaths["star"]?.hasSuffix(".png") ?? false

(More examples in the comments to the question.)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

swift optional chaining with cast

From Dev

Optional chaining with Swift strings

From Dev

Optional chaining and Array in swift

From Dev

optional chaining in Swift 3: why does one example work and not the other?

From Dev

Optional Chaining or ternary expression in Swift?

From Dev

Swift optional chaining doesn't work in closure

From Dev

Is there something like the swift optional chaining in javascript?

From Dev

Optional chaining used in left side of assignment in Swift

From Dev

Accessing boolValue in a NSNumber var with optional chaining (in Swift)

From Dev

Swift indexpath = optional(0)

From Dev

How to use optional chaining while searching through a dictionary in swift?

From Dev

Is Swift optional chaining lazily evaluated left-to-right?

From Dev

Swift 3 optional unwrapping

From Dev

Swift 3 optional parameters

From Dev

Chaining closures and completion handlers Swift 3

From Dev

In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional?

From Dev

Is Swift optional chaining always done with the if let construction, or is it just done using a question mark with an optional?

From Dev

In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional?

From Java

Optional chaining (?.) in nashorn

From Dev

Optional Chaining returning an Int

From Dev

Optional Chaining in JavaScript

From Dev

Optional Chaining Not Working As Expected

From Dev

Chaining Optional.orElseThrow

From Dev

Optional chaining for constructor calls?

From Dev

Optional struct in Swift3

From Dev

Swift 3: How to read from "Optional(Optional(stringValue))" without optional?

From Dev

an unexpected error while writing a piece of code from Swift programming by Apple(optional chaining)

From Dev

Optional chaining not working for optional protocol requirements

From Dev

Is there an equivalent to optional chaining with arithmetic operators?

Related Related

  1. 1

    swift optional chaining with cast

  2. 2

    Optional chaining with Swift strings

  3. 3

    Optional chaining and Array in swift

  4. 4

    optional chaining in Swift 3: why does one example work and not the other?

  5. 5

    Optional Chaining or ternary expression in Swift?

  6. 6

    Swift optional chaining doesn't work in closure

  7. 7

    Is there something like the swift optional chaining in javascript?

  8. 8

    Optional chaining used in left side of assignment in Swift

  9. 9

    Accessing boolValue in a NSNumber var with optional chaining (in Swift)

  10. 10

    Swift indexpath = optional(0)

  11. 11

    How to use optional chaining while searching through a dictionary in swift?

  12. 12

    Is Swift optional chaining lazily evaluated left-to-right?

  13. 13

    Swift 3 optional unwrapping

  14. 14

    Swift 3 optional parameters

  15. 15

    Chaining closures and completion handlers Swift 3

  16. 16

    In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional?

  17. 17

    Is Swift optional chaining always done with the if let construction, or is it just done using a question mark with an optional?

  18. 18

    In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional?

  19. 19

    Optional chaining (?.) in nashorn

  20. 20

    Optional Chaining returning an Int

  21. 21

    Optional Chaining in JavaScript

  22. 22

    Optional Chaining Not Working As Expected

  23. 23

    Chaining Optional.orElseThrow

  24. 24

    Optional chaining for constructor calls?

  25. 25

    Optional struct in Swift3

  26. 26

    Swift 3: How to read from "Optional(Optional(stringValue))" without optional?

  27. 27

    an unexpected error while writing a piece of code from Swift programming by Apple(optional chaining)

  28. 28

    Optional chaining not working for optional protocol requirements

  29. 29

    Is there an equivalent to optional chaining with arithmetic operators?

HotTag

Archive