【发布时间】:2016-09-09 01:23:45
【问题描述】:
我有多个具有相同静态变量的类。我在运行时获得每个类的 currentInstance(AnyObject?)。然后我试图通过使用 type(of: instance) 方法从实例中获取一个类来访问静态变量。但是当试图获取静态变量时,它会抛出一个错误 - Value of type 'AnyObject.Type' has no member 。这是伪代码。
public extension Reader {
open static var funcDictionary = [String: readerFuncs]() //ReaderFuncs is an enum of functions
}
public extension Library {
open static var funcDictionary = [String: libraryFuncs]()
}
public extension ReaderMenu {
open static var funcDictionary = [String: readerMenuFuncs]()
}
import Foundation
open class TestClass: NSObject {
open func executeFunction(currentInstance: AnyObject) { // I get current instance at runtime. And I have checked that I get the correct value
var count = type(of: currentInstance).functionDictionary.count // Error: Value of type 'AnyObject.Type' has no member funcDictionary
}
我想知道当你只有类的实例可用时如何访问静态变量。我也使用过 .classforCoder() 但它不起作用。所有文件也具有相同的目标成员资格。
【问题讨论】:
-
您将不得不创建一个需要
open static var funcDictionary的协议,然后将您的TestClass 函数更改为open func executeFunction<T: ProtocolName>(currentInstance: T)。然后,您可以使用T.functionDictionary.count,而不是使用type(of: -
你的枚举是什么样的?
-
我已经更新了我的答案并在操场上进行了测试,如果它适合你,请告诉我。