Search code examples
swiftcastingoption-typeanyobject

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?


Solution

  • 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")
    }