Reputation: 11
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
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
andprint(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.
Upvotes: 3