Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Paul Je
Paul Je
4,435 Points

What's the difference between an Any and an AnyObject again? Are there some examples of when each will be used?

Not sure how they differ, thanks in advance!

1 Answer

Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,497 Points

Heres something i saw online at: https://craiggrummitt.wordpress.com/2016/07/05/any-vs-anyobject-vs-nsobject/

An example:

If you specifically define the array as [Any], you are indicating to the compiler that you are aware that the elements are not of the same data type, and you are ok with that.

class Test {}
//No error, test is defined as [Any]
var test:[Any] = [Test(),"a",0]

You may be surprised to learn that unlike NSObject, Any is not actually a concrete data type. You won’t find a type description for it in documentation. Rather Any is an alias for any data type.

Similarly, AnyObject is an alias for any data type derived from a class. You can use it to define an array that contains more than one object derived from a class, that don’t share a common root class:

class Test {}
class Test2 {}
//No error, test is defined as [AnyObject]
var test:[AnyObject] = [Test(),Test2()]

(You could of course have used [Any] as well – [AnyObject] is just a little more specific.

[MOD: edited code blocks - sh]