【问题标题】:What is the best way in Swift 4+ to store a set of homogenous arrays for various types in a dictionary?在 Swift 4+ 中为字典中的各种类型存储一组同质数组的最佳方法是什么?
【发布时间】:2019-04-23 06:16:20
【问题描述】:

考虑一种情况,我们想要一个数组字典,每个数组都是某种类型(可能是结构或原始类型)值的同质集合。我目前正在使用定义它的类型的 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
]

这里的问题是,在遍历数据结构时,Swift 并不知道每个列表中的对象是同质的。由于 swift 是静态类型的,我猜不可能使用 ObjectIdentifier 键对 [Any] 列表进行类型转换。考虑这个遍历伪代码:

for (typeObjId, listOfValuesOfSometype) in myDataStructure {
   // do something like swap values around in the array,
   // knowing they are homogeneously but anonymously typed
}

那么,是否有一些元类型机制我可以用某种方式来表示这个数据结构,而不是预期其中包含数组的实际类型列表?

【问题讨论】:

  • 具有关联类型的枚举是一个选项吗?例如enum ObjectIdentifier { case ints([UInt32]), floats([Float]), bools([Bool]) }
  • 有趣的问题。我认为这也不可能。你为什么需要这个?也许有不同的方式来实现你的实际目标。

标签: swift dictionary metatype


【解决方案1】:

我不确定你想要完成什么,在字典循环中,数组将始终是 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] ?? []
}

【讨论】:

    猜你喜欢
    • 2018-03-15
    • 1970-01-01
    • 2018-06-01
    • 2016-01-03
    • 2022-09-27
    • 2016-04-26
    • 2020-04-08
    • 2011-08-09
    • 2011-03-20
    相关资源
    最近更新 更多