3

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?

Jan Nash
  • 1,883
  • 19
  • 30

2 Answers2

6

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")
}
Johannes
  • 564
  • 2
  • 7
  • 1
    Stupid me... "" is the description for an NSNull, long time since I've last had to work with ObjectiveC and I rarely use NSNulls in Swift... – Jan Nash May 29 '18 at 09:02
2

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

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69