Reputation: 1962
I'm struggling to understand the behaviour of the following code:
let a: Any? = nil
let b: AnyObject? = a as AnyObject
if let c: AnyObject = b {
print(c)
print("That's not right, is it?")
} else {
print("I'd expect this to be printed")
}
When run in a playground, although a is nil, the first closure is executed and prints the following:
<null>
That's not right, is it?
Q: How is this possible and is it expected behaviour?
Upvotes: 3
Views: 59
Reputation: 36401
Because <null>
is not nil
. AnyObject
is a type that bridges to Objective-C space.
Upvotes: 2
Reputation: 586
a as AnyObject
will cast a
to NSNull
so that b
is not nil
You can check it with type(of:)
let a: Any? = nil
let b: AnyObject? = a as AnyObject
if let c: AnyObject = b {
print(c)
print(type(of: c)) // will print "NSNull"
print("That's not right, is it?")
} else {
print("I'd expect this to be printed")
}
Upvotes: 6