Optional chaining with Swift strings

Stephen Schaub

With optional chaining, if I have a Swift variable

var s: String?

s might contain nil, or a String wrapped in an Optional. So, I tried this to get its length:

let count = s?.characters?.count ?? 0

However, the compiler wants this:

let count = s?.characters.count ?? 0

My understanding of optional chaining is that, once you start using ?. in a dotted expression, the rest of the properties are made optional and are typically accessed by ?., not ..

So, I dug a little further and tried this in the playground:

var s: String? = "Foo"
print(s?.characters)
// Output: Optional(Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x00000001145e893f, _countAndFlags: 3, _owner: nil)))

The result indicates that s?.characters is indeed an Optional instance, indicating that s?.characters.count should be illegal.

Can someone help me understand this state of affairs?

Abizern

When you say:

My understanding of optional chaining is that, once you start using ?. in a dotted expression, the rest of the properties are made optional and are typically accessed by ?., not ..

I would say that you are almost there.

It’s not that all the properties are made optional, it’s that the original call is optional, so it looks like the other properties are optional.

characters is not an optional property, and neither is count, but the value that you are calling it on is optional. If there is a value, then the characters and count properties will return a value; otherwise, nil is returned. It is because of this that the result of s?.characters.count returns an Int?.

If either of the properties were optional, then you would need to add ? to it, but, in your case, they aren’t. So you don’t.


Edited following comment

From the comment:

I still find it strange that both s?.characters.count and (s?.characters)?.count compile, but (s?.characters).count doesn't. Why is there a difference between the first and the last expression?

I’ll try and answer it here, where there is more room than in the comment field:

s?.characters.count

If s is nil, the whole expression returns nil, otherwise an Int. So the return type is Int?.

(s?.characters).count // Won’t compile

Breaking this down: if s is nil, then (s?.characters) is nil, so we can’t call count on it.

In order to call the count property on (s?.characters), the expression needs to be optionally unwrapped, i.e. written as:

(s?.characters)?.count

Edited to add further

The best I can get to explaining this is with this bit of playground code:

let s: String? = "hello"

s?.characters.count
(s?.characters)?.count
(s)?.characters.count
((s)?.characters)?.count

// s?.characters.count
func method1(s: String?) -> Int? {
    guard let s = s else { return nil }

    return s.characters.count
}

// (s?.characters).count
func method2(s: String?) -> Int? {
    guard let c = s?.characters else { return nil }

    return c.count
}

method1(s)
method2(s)

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 3.0 Optional Chaining

From Dev

swift optional chaining with cast

From Dev

Optional chaining and Array in swift

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

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

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

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 Dev

Proper way to concatenate optional swift strings?

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

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?

From Dev

dynamicType of optional chaining not the same as assignment

From Dev

Optional.ofNullable and method chaining

From Dev

Swift 2 - Optional Strings Appear upon Automatic Location

From Dev

Swift with Core Data getting an "Optional("")" on the strings i am fetching?

From Dev

Swift - Method chaining

Related Related

  1. 1

    Swift 3.0 Optional Chaining

  2. 2

    swift optional chaining with cast

  3. 3

    Optional chaining and Array in swift

  4. 4

    Optional Chaining or ternary expression in Swift?

  5. 5

    Swift optional chaining doesn't work in closure

  6. 6

    Is there something like the swift optional chaining in javascript?

  7. 7

    Optional chaining used in left side of assignment in Swift

  8. 8

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

  9. 9

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

  10. 10

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

  11. 11

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

  12. 12

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

  13. 13

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

  14. 14

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

  15. 15

    Proper way to concatenate optional swift strings?

  16. 16

    Optional chaining (?.) in nashorn

  17. 17

    Optional Chaining returning an Int

  18. 18

    Optional Chaining in JavaScript

  19. 19

    Optional Chaining Not Working As Expected

  20. 20

    Chaining Optional.orElseThrow

  21. 21

    Optional chaining for constructor calls?

  22. 22

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

  23. 23

    Optional chaining not working for optional protocol requirements

  24. 24

    Is there an equivalent to optional chaining with arithmetic operators?

  25. 25

    dynamicType of optional chaining not the same as assignment

  26. 26

    Optional.ofNullable and method chaining

  27. 27

    Swift 2 - Optional Strings Appear upon Automatic Location

  28. 28

    Swift with Core Data getting an "Optional("")" on the strings i am fetching?

  29. 29

    Swift - Method chaining

HotTag

Archive