CocoaUser
CocoaUser

Reputation: 1429

Swift issue: About Type Casting for AnyObject

Swift provides two special type aliases for working with non-specific types:
AnyObject can represent an instance of any class type.

according official document: reference above and thinking about below case

class Person {
   var name = "new name"

   init(name: String) {
       self.name = name  
   }
}

var people: [AnyObject] = [Person(name: "Allen"), Person(name: "Hank"), 23]

Why? I can add 23 (Int is a struct) into people array?

Upvotes: 1

Views: 315

Answers (1)

Nate Cook
Nate Cook

Reputation: 93276

This is a little confusing because of the bridging that Swift does to Objective-C, where most things are classes and there are fewer value-types. To see what Swift does without the bridge, create a new playground and delete the import ... statement at the top, then try casting an Int to Any (no problem) and AnyObject:

let num = 23                               // 23
let anyNum: Any = num                      // 23
let anyObjectNum: AnyObject = num
// error: type 'Int' does not conform to protocol 'AnyObject'

Now add import Foundation at the top of your playground:

import Foundation

let num = 23                               // 23
let anyNum: Any = num                      // 23
let anyObjectNum: AnyObject = num          // 23

The error goes away - why? When it sees the attempt to cast an Int to AnyObject, Swift first bridges num to be an instance of the Objective-C NSNumber class, found in Foundation, then casts it to the desired AnyObject. The same thing is happening in your array.

You can more or less prove this is the case using the is keyword - since NSNumber bridges to all the numeric types in Swift, it returns true in some funny cases:

anyNum is Int                              // true
anyNum is Double                           // false
anyObjectNum is Int                        // true
anyObjectNum is UInt                       // true
anyObjectNum is Double                     // true
anyObjectNum is Float                      // true

Upvotes: 4

Related Questions