如何快速创建抽象的不可变列表,例如Kotlin

当我将Kotlin代码更改为Swift代码时。我在创建抽象不可变列表时遇到问题。

private interface A{
    val Id : Int
    val anotherValue : Int
}

private val anotherList : ArrayList<A>

override val idList: List<Int>
    get() = object : AbstractList<Int>() {
        override val size: Int
            get() = anotherList.size

        override fun get(index: Int): Int {
            return anotherList[index].Id
        }
    }

这段代码是在调用“ idList”属性时创建的“ AbstractList”。我打算不占用创建的实例自身之外的任何其他容量。

我尝试在Swift上迁移代码,如下所示:

override var idList: [Int]{
    return self.anotherList.map{
        $0.Id
    }
}

但是,此代码占用更多的内存,例如列表复制。我能怎么做?

清扫器

您可以使用lazy地图:

let idList: LazyMapSequence<[A], Int> {
    self.anotherList.lazy.map(\.id)
}

我很确定可以lazy为您提供一个懒惰的“视图”数组。并且由于这是一个惰性序列,因此在您需要ID之前不会对其进行计算。另外,由于数组是随机访问的,因此,如果您需要第三个id,则不会计算第一个和第二个id。

另外,我认为这更好,编写自己的ArrayKeyPathView收藏集:

struct ArrayKeyPathView<WrappedElement, KeyPathType> : RandomAccessCollection {
    subscript(position: Int) -> Element {
        get {
            wrapped[position][keyPath: keyPath]
        }
    }
    
    var startIndex: Int {
        wrapped.startIndex
    }
    
    var endIndex: Int {
        wrapped.endIndex
    }
    
    
    var indices: Range<Int> {
        wrapped.indices
    }
    
    typealias Index = Int
    typealias SubSequence = ArrayKeyPathView
    typealias Element = KeyPathType
    typealias Indices = Range<Int>
    
    private let wrapped: [WrappedElement]
    private let keyPath: KeyPath<WrappedElement, KeyPathType>
    
    init(_ array: [WrappedElement], keyPath: KeyPath<WrappedElement, KeyPathType>) {
        self.wrapped = array
        self.keyPath = keyPath
    }
}

用法:

let idList: ArrayKeyPathView<A, Int> {
    ArrayKeyPathView(self.anotherList, keyPath: \.id)
}

由于快速数组是写时复制的,因此仅将其传递给ArrayKeyPathView副本就不会创建副本。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章