Swift "AnyClass" Type

TL;DR you're looking for MyClass.self

When working with ConnectSDK, I came across something I hadn't before in Swift: the AnyClass type. ConnectSDK is an Objective-C based library so I'd imagine this is a rarity when working with native Swift code.

Here's what it looks like:

discoveryManager?.registerDeviceService(deviceClass: AnyClass!, withDiscovery: AnyClass!)

I mistakenly though it was looking for an instance (i.e. MyClass()) but that threw an error. It turns out that in Objective-C each class has the static class property. In the case of ConnectSDK it's looking for the following:

[AirPlayService class]
[DIALService class]
[CastService class]

This class property doesn't exist in Swift. It just flat-out hasn't got a clue what do to with it.

Computer says no

AnyClass is basically asking for the type of the class. This is known as the Metatype Type in swift and refers to the type of any type (inception).

In our case this is AirPlayService, DIALService or CastService. We can get this out of the class as a value using the self expression:


Here's what that looks like when used in our ConnectSDK example.

discoveryManager?.registerDeviceService(CastService.self, withDiscovery: CastDiscoveryProvider.self)

Learn more about the Metatype type on Apple's website.

Want to say "Hello"? Drop me an email, follow me on Twitter, or check out Cocoon (you totally should, we're doing some cool stuff over there).