1

I have observed that it is possible to use the subscript operator with AnyObject instances in Swift. For example:

let x: AnyObject = NSDictionary()

print(type(of: x["y"]))

This code produces the following output:

ImplicitlyUnwrappedOptional<Optional<Any>>

The first part makes sense, because invoking any method on an instance of AnyObject is defined to behave like an implicitly unwrapped optional. The rest of the output suggests that the subscript operator itself is defined to return Optional<Any>, which also makes sense, since it parallels the behavior of subscripts for dictionary instances.

I assume this is by design, but I haven't been able to verify it. Does anyone know if the behavior of the subscript operator for AnyObject is documented anywhere?

Greg Brown
  • 3,168
  • 1
  • 27
  • 37
  • `let x: AnyObject = NSDictionary()` is insane. With the annotation you cast a - in terms of Swift - already quite unspecified type `NSDictionary` which is at least recognized as key subscriptable to a completely unspecified type `AnyObject`. **`AnyObject` can not be subscripted at all**. If you are looking for a language which **does not** care about types Swift is not a candidate. – vadian Mar 30 '17 at 21:29
  • It's just an example. Obviously you'd never create an `NSDictionary` and assign it to `AnyObject` in practice. However, it's perfectly valid to end up with an instance of `AnyObject` in Swift; for example, when using `JSONSerialization`. And yes, you absolutely can subscript `AnyObject` - hence, my question. – Greg Brown Mar 30 '17 at 22:43
  • When deserializing JSON you don't need `AnyObject / Any` at all. JSON contains only two collection types, array `[Any]` and dictionary `[String:Any]`. The former can be subscripted by index, the latter by key. The main concept of Swift is the strong type system so never cast or annotate a type to a more unspecific one unless the compiler tells you to do. – vadian Mar 31 '17 at 04:39
  • I'm aware of how JSON and Swift's type system works. I'm simply asking if the behavior of the sequence operator with AnyObject is documented anywhere. – Greg Brown Mar 31 '17 at 10:37

0 Answers0