Swift -如何通过方法调用传递类型?

时间:2021-06-14 09:22:45

A Realm object:

领域对象:

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

Calling results:

调用结果:

let results = realm.objects(Dog)

Or doing it this way:

或者这样做:

let type = Dog.self
let results = realm.objects(type)

I want to be able to do it by passing into a method like this:

我想通过这样的方法来实现

class SomeClass {
  func callRealm(type: AnyObject) {
    let results = realm.objects(type)
  }
}

let someClass = SomeClass()
let type = Dog.self
someClass.callRealm(type)

How would I do this? I've had no luck with generics, although I think this might be the way to go.

我该怎么做呢?我不喜欢泛型,尽管我认为这可能是一条路。

1 个解决方案

#1


2  

Your function callRealm should take input as AnyClass instead of AnyObject.

函数调用域应该将输入作为any类而不是AnyObject。

func callRealm(type: AnyClass) {
    let results = realm.objects(type)
  }

#1


2  

Your function callRealm should take input as AnyClass instead of AnyObject.

函数调用域应该将输入作为any类而不是AnyObject。

func callRealm(type: AnyClass) {
    let results = realm.objects(type)
  }