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?



Swift defines the AnyObject type alias to represent instances of any reference type, and it’s ..

Answer / iosraj

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.

Is This Answer Correct ?    1 Yes 0 No

Post New Answer

More Apple iOS Swift Interview Questions

struct Planet { var name: String var distanceFromSun: Double } let planets = [ Planet(name: "Mercury", distanceFromSun: 0.387), Planet(name: "Venus", distanceFromSun: 0.722), Planet(name: "Earth", distanceFromSun: 1.0), Planet(name: "Mars", distanceFromSun: 1.52), Planet(name: "Jupiter", distanceFromSun: 5.20), Planet(name: "Saturn", distanceFromSun: 9.58), Planet(name: "Uranus", distanceFromSun: 19.2), Planet(name: "Neptune", distanceFromSun: 30.1) ] let result1 = planets.map { $0.name } let result2 = planets.reduce(0) { $0 + $1.distanceFromSun } What are the types and values of the result1 and result2 variables? Explain why.

1 Answers  


What is clean swift architecture?

0 Answers  


What is weak in swift?

0 Answers  


Is swift similar to c?

0 Answers  


Explain enum in swift.

0 Answers  






What collection types are available in swift?

0 Answers  


What is the difference between function and method in swift?

0 Answers  


How much do swift developers make?

0 Answers  


How to make a method or variable generics in swift?

0 Answers  


How will you define base class?

0 Answers  


Can enum conform to swift protocol?

0 Answers  


Does swift have abstract classes?

0 Answers  


Categories