user2143356
user2143356

Reputation: 5607

How do I specify class name as variable in Swift?

I want to do something like this:

class Dog: Object {
  dynamic var name = ""
  dynamic var age = 0
}

let results = realm.objects(Dog)

...but specify the object name as a variable.

This doesn't work:

let objectName = "Dog"
let results = realm.objects(objectName)

Neither does this:

let object = Dog
let results = realm.objects(object)

...or this:

let object = Dog()
let results = realm.objects(object)

...or this:

let object: Dog
let results = realm.objects(object)

Any ideas?

Upvotes: 0

Views: 585

Answers (1)

Charles A.
Charles A.

Reputation: 11143

You can reference the type directly with Dog.self:

let type = Dog.self

I don't have a project with realm, but in theory you should then be able to do something like:

let results = realm.objects(type)

Upvotes: 1

Related Questions