Strange Any? as AnyObject behaviour

63 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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")
}
0
On

Because <null> is not nil. AnyObject is a type that bridges to Objective-C space.