richar lee
richar lee

Reputation: 11

A little question about optional chaining in swift

I run these codes in the playground, but I get a compile error with

a.b.b = 3

but it runs well at the next line. What's the difference between these two? When should I use the '!' explicitly and when it's not necessary?

Here are the codes:

class A {
    var a = 1
    var b = B()
}

class B {
    var b = 2
}

var a:A! = A()

a.b.b = 3 // will get a compile error
print(a.b.b) // runs well, print 2
a?.b.b = 3 // runs well
print(a.b.b) // runs well, print 3

Upvotes: 1

Views: 189

Answers (1)

Glenn Posadas
Glenn Posadas

Reputation: 13300

Welcome to Stackoverflow. Let's try to answer your questions one by one.

What's the difference between these two? a.b.b = 3 and print(a.b.b)

If this is what you mean, the first one causes an error on Playground,

expression failed to parse, unknown error

then actually there's no difference. But if you wanna know why this happens, it must be a Playground issue. Because this expression should not cause a compile-time error in Xcode (project).

To solve that in Playground, you need to breakdown your expression, like so:

let bOfA = a.b
bOfA.b = 3

Voila! Problem solved!

Also, this issue might be somehow connected with the Xcode error:

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions


When should I use the '!' explicitly and when it's not necessary?

You use that ! if you are sure that your object is has a value. ! automatically unwraps the object, without having to check whether it is nil or not.

When it's not necessary? Well, as much as possible, you shouldn't practice force-unwrapping. Read on safe unwrapping optionals for more info. There are lots of resources out there about it.

  1. Swift safely unwrapping optinal strings and ints
  2. https://learnappmaking.com/swift-optionals-how-to/
  3. https://forums.developer.apple.com/thread/45469

Upvotes: 3

Related Questions