问题
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?
回答1:
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)
来源:https://stackoverflow.com/questions/32915093/how-do-i-specify-class-name-as-variable-in-swift