Gregory Higley
Gregory Higley

Reputation: 16558

What types cannot be cast to `AnyObject` in Swift 4?

I've experimented with casting many types to AnyObject. Reference types obviously cast unaltered, but others are automagically converted under the hood to NSNumber, NSValue, and so on. (These are not the exact types, but close enough.) I was even able to cast a tuple successfully.

This surprised me. Are there any types that cannot be cast to AnyObject?

There are other questions and answers that may cover this material, but none of them asks this question specifically and the answer to this question can only be found in the fine print of the other answers.

Upvotes: 1

Views: 565

Answers (1)

matt
matt

Reputation: 534925

AnyObject is Objective-C id, meaning any class type. Casting to AnyObject means "wrap this up in a way that Objective-C can deal with as a class type."

Obviously, an NSObject subclass just crosses the bridge directly.

For other types (i.e. nonclasses), Swift 4 follows three policies:

  • Some types are bridged directly to classes, e.g. String to NSString.

  • Some types are wrapped in Objective-C class types, e.g. Int in NSNumber or CGRect in NSValue.

  • All other types are boxed in an opaque wrapper; they can cross the bridge to Objective-C, and can be round-tripped successfully back to Swift, but nothing useful can be done with them in the Objective-C world.

Upvotes: 4

Related Questions