Foo*_*man 7 dictionary swift metatype
考虑一种我们希望拥有数组字典的情况,每个数组都是某种类型的值的同类集合(可以是结构或基本类型).我目前正在使用定义它的类型的ObjectIdentifier:
let pInts : [UInt32] = [4, 6, 99, 1001, 2032]
let pFloats : [Float] = [3.14159, 8.9]
let pBools : [Bool] = [true, false, true]
let myDataStructure : [ObjectIdentifier : [Any]] = [
ObjectIdentifier(Float.self) : pFloats,
ObjectIdentifier(UInt32.self) : pInts,
ObjectIdentifier(Bool.self) : pBools
]
Run Code Online (Sandbox Code Playgroud)
这里的问题是,当遍历数据结构时,Swift不知道每个列表中的对象是同构的.由于swift是静态类型的,我猜测不可能[Any]使用ObjectIdentifier键对列表进行类型转换.考虑这个遍历伪代码:
for (typeObjId, listOfValuesOfSometype) in myDataStructure {
// do something like swap values around in the array,
// knowing they are homogeneously but anonymously typed
}
Run Code Online (Sandbox Code Playgroud)
那么,是否有一些元类型机制可以编写代表这种数据结构的方式,它不会预期将有数组的实际类型列表?
我不太确定你想要完成什么,在字典循环内,数组将始终是 Any 类型,但如果你想移动数组中的项目,你可以这样做。只需首先将数组重新分配给 var,然后将其放回字典中即可。
如果您确实想循环特定类型的项目,那么您可以使用下面的数组辅助函数。
func testX() {
let pInts: [UInt32] = [4, 6, 99, 1001, 2032]
let pFloats: [Float] = [3.14159, 8.9]
let pBools: [Bool] = [true, false, true]
var myDataStructure: [ObjectIdentifier: [Any]] = [
ObjectIdentifier(Float.self): pFloats,
ObjectIdentifier(UInt32.self): pInts,
ObjectIdentifier(Bool.self): pBools
]
// Swap the first 2 items of every array
for d in myDataStructure {
var i = d.value
if i.count > 1 {
let s = i[0]
i[0] = i[1]
i[1] = s
}
myDataStructure[d.key] = i
}
// Now dump all data per specific type using the array helper function.
for i: UInt32 in array(myDataStructure) {
print(i)
}
for i: Float in array(myDataStructure) {
print(i)
}
for i: Bool in array(myDataStructure) {
print(i)
}
}
func array<T>(_ data: [ObjectIdentifier: [Any]]) -> [T] {
return data[ObjectIdentifier(T.self)] as? [T] ?? []
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |