Jan Nash
Jan Nash

Reputation: 1962

Strange Any? as AnyObject behaviour

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

Answers (2)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

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

Upvotes: 2

Johannes
Johannes

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

Related Questions