Generics vs AnyObject vs Any

Hi Codebugs,
Today we will speak about AnyObject and generics. What is AnyObject anyway?
In simple terms, AnyObject is Swift's analogue to Objective-C's id.

Consider two functions, one with generics, the other with Any both of which just return the input argument:

   func operation<T>(x: T) -> T {
      return x
   }
   func operation(x: Any) -> Any { 
      return x
   }

The first function, preserves the type of the input argument for us thanks to generics. If we pass in an Int, it returns an Int because the compiler can infer the return type.

The second version of this function dodges the Swift type system and you the type of x is completely lost after returning the value.We should try to avoid it. AnyObject is there for the times when we are working with Cocoa APIs because it is common to receive an array with a type of [AnyObject].

Also, as a side note it may be a good time to consult the Apple documentation on the difference between Any and AnyObject:

Swift provides two special type aliases for working with non-specific types:

  • AnyObject can represent an instance of any class type.
  • Any can represent an instance of any type at all, including function types.

There it is, we now know what is Any, AnyObject and Generics are and their intended purpose. Happy coding, bugs :)

The Code Bug

A passionate iOS developer. Looking to radically improve the way we all develop software.

Amsterdam