How do I specify class name as variable in Swift?

◇◆丶佛笑我妖孽 提交于 2021-02-11 12:09:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!