假设我有一个名为LivingCreature
And的其他类继承自它的类:
Human
Dog
Alien
这就是我想要完成的事情:
let valueForLivingCreature = Dictionary<Alien, String>
Run Code Online (Sandbox Code Playgroud)
并像这样访问它:
let alienValue = livingCreatureForValue[Alien]
Run Code Online (Sandbox Code Playgroud)
但这意味着类应该符合Equatable和Hashable,但类本身,而不是类实例.我已经尝试了各种方法来实现这一点,但没有运气.
作为妥协,我想出的是:
typealias IndexingValue = Int
class LivingCreature {
static var indexingValue: IndexingValue = 0
}
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样使用类作为键:
let livingCreatureForValue = Dictionary<IndexingValue, String>
Run Code Online (Sandbox Code Playgroud)
访问:
let alienValue = livingCreatureForValue[Alien.indexingValue]
Run Code Online (Sandbox Code Playgroud)
但是,这样就应该手动为每个类设置IndexingValue.我想像这样从类本身做一个哈希:
class LivingCreature {
static var indexingValue: IndexingValue {
return NSStringFromClass(self).hash
}
}
Run Code Online (Sandbox Code Playgroud)
这是不可能的,因为self无法访问静态var.
我的问题是,有没有更好的方法来解决这类问题?
编辑:
@Paulw11问我为什么不让LivingCreature确认Equatable和Hashable,原因是我无法通过类类型引用访问该值.我每次都要分配一个实例:
let alienValue = livingCreatureForValue[Alien()]
Run Code Online (Sandbox Code Playgroud)
我不想每次都找"Alien()"来寻找价值.而使用它的组件,不关心livingCreature实例,只关心类类型.
我假设你正在尝试这样的事情:
let valueForLivingCreature = Dictionary<LivingCreature.Type, String>
Run Code Online (Sandbox Code Playgroud)
和:
let alienValue = valueForLivingCreature[Alien.self]
Run Code Online (Sandbox Code Playgroud)
然后你可以使用ObjectIdentifier:
class LivingCreature {
class var classIdentifier: ObjectIdentifier {
return ObjectIdentifier(self)
}
//...
}
class Human: LivingCreature {
//...
}
class Dog: LivingCreature {
//...
}
class Alien: LivingCreature {
//...
}
let valueForLivingCreature: Dictionary<ObjectIdentifier, String> = [
Human.classIdentifier: String(Human),
Dog.classIdentifier: String(Dog),
Alien.classIdentifier: String(Alien),
]
let alienValue = valueForLivingCreature[Alien.classIdentifier] //->"Alien"
Run Code Online (Sandbox Code Playgroud)
但是在大多数用例中,当你想使用元类作为字典键时,你可以找到另一种方法:
class LivingCreature {
class var classValue: String {
return String(self)
}
//...
}
class Human: LivingCreature {
//...
//Override `classValue` if needed.
}
class Dog: LivingCreature {
//...
}
class Alien: LivingCreature {
//...
}
let alienValue = Alien.classValue //->"Alien"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
558 次 |
| 最近记录: |