问题描述
我正在尝试这样做。
static var recycle: [Type: [CellThing]] = []
但是我不能:)
在示例中, CellThing
是我的基类,所以 A:CellThing
, B:CellThing
, C:CellThing
等等。这个想法是我会将各种AAA,BB,CCCC存储在字典数组中。
In the example, CellThing
is my base class, so A:CellThing
, B:CellThing
, C:CellThing
and so on. The idea is I would store various A A A, B B, C C C C in the dictionary arrays.
如何使类型(理想情况下,我猜到,限制在CellThing)成为Swift字典中的关键?
How to make a "Type" (ideally I guess, constrained to CellThing) be the key in a Swift dictionary?
我感谢我可以(也许?)使用 String(描述:T.self )
,但这会让我失眠。
I appreciate I could (perhaps?) use String(describing: T.self)
, but that would make me lose sleep.
这是一个用例,设想的代码会看起来像这样...
Here's a use case, envisaged code would look something like this ...
@discardableResult class func make(...)->Self {
return makeHelper(...)
}
private class func makeHelper<T: CellThing>(...)->T {
let c = instantiateViewController(...) as! T
return c
}
所以, p>
So then something like ...
static var recycle: [Type: [CellThing]] = []
private class func makeHelper<T: CellThing>(...)->T {
let c = instantiateViewController(...) as! T
let t = type whatever of c (so, maybe "A" or "B")
recycle[t].append( c )
let k = recycle[t].count
print wow, you have k of those already!
return c
}
推荐答案
不幸的是,目前,metatype类型不符合协议(请参阅) - 所以 CellThing.Type
不,并且不能,目前符合 Hashable
。因此,这意味着它不能直接用作字典
中的键
。
Unfortunately, it's currently not possible for metatype types to conform to protocols (see this related question on the matter) – so CellThing.Type
does not, and cannot, currently conform to Hashable
. This therefore means that it cannot be used directly as the Key
of a Dictionary
.
但是,您可以使用,以便提供 Hashable
实现。例如:
However, you can create a wrapper for a metatype, using ObjectIdentifier
in order to provide the Hashable
implementation. For example:
/// Hashable wrapper for a metatype value.
struct Metatype<T> : Hashable {
static func ==(lhs: Metatype, rhs: Metatype) -> Bool {
return lhs.base == rhs.base
}
let base: T.Type
init(_ base: T.Type) {
self.base = base
}
var hashValue: Int {
return ObjectIdentifier(base).hashValue
}
}
class CellThing {
// convenience static computed property to get the wrapped metatype value.
static var metatype: Metatype<CellThing> {
return Metatype(self)
}
}
class A : CellThing {}
class B : CellThing {}
var recycle: [Metatype<CellThing>: [CellThing]] = [:]
recycle[A.metatype] = [A(), A(), A()]
recycle[B.metatype] = [B(), B()]
print(recycle[A.metatype]!) // [A, A, A]
print(recycle[B.metatype]!) // [B, B]
这也应该适用于泛型,您只需将您的字典下标为 T.metatype
。
This should also work fine for generics, you would simply subscript your dictionary with T.metatype
instead.
这篇关于做一个Swift字典,其中的键是“Type”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!