Question:

Swift defines the AnyObject type alias to represent instances of any reference type, and it’s internally defined as a protocol.

Consider the following code:

var array = [AnyObject]()
struct Test {}
array.append(Test())

This code generates a compilation error, with the following error message:

Type 'Test' does not conform to protocol 'AnyObject'

The failure is obvious because a struct is a value and not a reference type, and as such it doesn’t implement and cannot be cast to the AnyObject protocol.

Now consider the following code:

var array = [AnyObject]()
array.append(1)
array.append(2.0)
array.append("3")
array.append([4, 5, 6])
array.append([7: "7", 8: "8"])

struct Test {}
array.append(Test())

The array array is filled in with values of type respectively int, double, string, array and dictionary. All of them are value types and not reference types, and in all cases no error is reported by the compiler. Why?

Answer:

The reason is that swift automatically bridges:

  • number types to NSNumber
  • strings to NSString
  • arrays to NSArray
  • dictionaries to NSDictionary

which are all reference types.


Keywords:

© 2017 QuizBucket.org