Alexey  Milahin Alexey Milahin - 7 months ago 10
Swift Question

How to check what class belongs AnyObject?

For example, there are two models Realm Information

import Foundation
import RealmSwift

class Music: Object {

dynamic var id = ""
dynamic var title = ""
dynamic var url = ""
}
class DownloadMusic: Object {

dynamic var id = ""
dynamic var title = ""
dynamic var path = ""
}


And there is a certain function

func test(object: AnyObject) {

}


When a call is transferred as an argument 'realm.objects(Music)[0]'

let realm = try! Realm()
test(realm.objects(Music)[0])


Can I check in function, the object belongs to a class 'Music' or to a 'DownloadMusic'

Answer

Try using .isKindOfClass(Music) or .isKindOfClass(DownloadMusic) methods

EDIT: as Jonathan pointed the correct way would be

if let musicObject = object as? Music

I tried to draw the analogy with Obj-C first, but then looked that in swift it's done differently