Pentarex
Pentarex

Reputation: 130

Swift 2.2 AnyObject Type

After the update of iOS 9.3 and the new update for Swift 2.2 (at least that was stated in the Xcode update changes) the code below doesn't work for me anymore.

if context[indexPath.row].dynamicType.className() == "MyClass"

it throws an exception which states:

Value of type 'AnyObject.Type' has no member 'className'

I am going through the changes which are described in swift.org but I can't find the answer of it.

Upvotes: 0

Views: 266

Answers (2)

JAL
JAL

Reputation: 42449

I don't know what className() does. It's not a known method on AnyClass.

There are a few ways you can fix this.

Use description() to get a String description of the class name:

if context[indexPath.row].dynamicType.description() == "MyClass" {
    // ...
}

Or if you're using Objective-C types you can use NSClassFromString to return an AnyClass from a String:

if context[indexPath.row].dynamicType == NSClassFromString("MyClass") {
    // ...
}

Swift 3:

dynamicType has been renamed to type(of:). Usage:

type(of: context[indexPath.row]) == MyClass.self

or

context[indexPath.row] is MyClass

Upvotes: 1

BaseZen
BaseZen

Reputation: 8718

Why bother with Strings when you have true compiler support in the type system itself? I recommend instead:

if context[indexPath.row].dynamicType == MyClass.Type.self {
    // ...
}

Also, it's quite likely that you really mean:

if let cell = context[indexPath.row] as? MyClass {
    // ...
}

unless you're intent on cutting out derived classes forever.

Upvotes: 3

Related Questions