有没有办法从Any获取Class(当Any是对象的实例时)?

时间:2018-04-25 13:42:35

标签: ios swift xcode

我想在我的应用中使用通用签名实现一个日志记录模块(缩短):

func log(msg: String, instance: Any) {}

我的应用程序由多个框架组成,我希望能够激活/停用每个框架的日志记录。从类中告诉框架(bundle)非常简单,如:

let bundle = Bundle(for: SomeClass.self)

所以我在func log()中尝试做的是:

let instance: Any = SomeClass() // This is for the purpose of explanation
if let theClass = type(of: instance) {
 let bundle = Bundle(for: theClass) // Doesn't work, because theClass is a metaType
}

在运行时是否有办法知道变量是否:Any是一个对象的实例并拥有AnyClass?

2 个答案:

答案 0 :(得分:2)

我相信以下内容应该足够了:

.*

事实上,只要您将let instance: Any = SomeClass() if let thisClass = type(of: instance) as? AnyClass { //is a class let bundle = Bundle(for: thisClass) print(bundle) } else { //is not a class } 对象正确地转换为instance,您就可以在AnyClass

中使用它

答案 1 :(得分:1)

你可以使用Mirror解决它:

let paperino: Paperino = Paperino()
let any = paperino as Any
let anyMirror = Mirror(reflecting: any)
let thisClass = anyMirror.subjectType
if let anyclass = thisClass as? AnyClass {
    print(Bundle(for: anyclass).bundleIdentifier!)
}