Value type is AnyObject! Why?

Can somebody explain this?

let array:[AnyObject] = []

if array is [Int] {
    print("// yes [AnyObject] is [Int]")
}

class Container<T> where T: AnyObject {
    init(value: T) {
        print("Initialize with object \(value)")
    }
}

and this

struct Cat {}

let cat = Cat()

class Container<T> where T: AnyObject {
    init(value: T) {
        print("Initialize with object \(value)")
    }
}
let container = Container(value: cat as AnyObject)

from here:

This is correct (albeit unintuitive at first) behaviour, and is a result of id-as-Any. See the following thread for more info:

Regarding your example with the array:

let array: [AnyObject] = []

if array is [Int] {
    print("// yes [AnyObject] is [Int]")
}

it's worth noting that currently empty arrays can be cast to any array type. For example:

let array: [String] = []

if array is [Int] {
  print("yup")
}
// prints: yup

There's some discussion of this behaviour in the comments of SR-6192.

Just funny compiler fact.

The compiler suggestion is totally incorrect:)

XCode Version 10.1 (10B61)

Terms of Service

Privacy Policy

Cookie Policy