Fat*_*tie 16 dictionary types swift
我正试图做这种事情..
static var recycle: [Type: [CellThing]] = []
Run Code Online (Sandbox Code Playgroud)
但是 - 我不能:)
未声明的类型'类型'
在这个例子中,CellThing
是我的基类,所以A:CellThing
,B:CellThing
,C:CellThing
等等.我的想法是将各种AAA,BB,CCCC存储在字典数组中.
如何制作一个"类型"(理想情况下我猜,限制在CellThing)是Swift字典中的关键?
我很欣赏我可能(也许?)使用String(describing: T.self)
,但这会让我失眠.
这是一个用例,设想的代码看起来像这样......
@discardableResult class func make(...)->Self {
return makeHelper(...)
}
private class func makeHelper<T: CellThing>(...)->T {
let c = instantiateViewController(...) as! T
return c
}
Run Code Online (Sandbox Code Playgroud)
那么就像......
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
}
Run Code Online (Sandbox Code Playgroud)
Ham*_*ish 23
不幸的是,目前不能使元类型类型符合协议(请参阅此问题的相关问题) - 所以CellThing.Type
当前不符合,也不能符合Hashable
.因此,这意味着它不能直接用作Key
a Dictionary
.
但是,您可以为元类型创建包装器ObjectIdentifier
,以便提供Hashable
实现.例如:
/// Hashable wrapper for a metatype value.
struct HashableType<T> : Hashable {
static func == (lhs: HashableType, rhs: HashableType) -> Bool {
return lhs.base == rhs.base
}
let base: T.Type
init(_ base: T.Type) {
self.base = base
}
func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(base))
}
// Pre Swift 4.2:
// var hashValue: Int { return ObjectIdentifier(base).hashValue }
}
Run Code Online (Sandbox Code Playgroud)
这也应该适用于泛型,你可以简单地下载你的字典Dictionary
.
归档时间: |
|
查看次数: |
4044 次 |
最近记录: |