需要:具有固定内存的Swift类作为数组

huangapple go评论47阅读模式
英文:

Wanted: Swift Class of fixed memory as array

问题

我需要一个类,为通用类型<T>分配内存块。它应该提供所有通常的功能,如索引、添加、排序等。但与内置功能相比,每个元素都不应该有动态内存分配。因此,它是一个相对静态的数组。我不想重复造轮子,所以我想知道是否已经有类似的库或插件等。有什么提示吗?

英文:

I need a class, which allocates a memory block for generic Type <T>. It should offer all usual features like indexing, adding, sort etc. But in contrast to the build in functionality, there should be no dynamic memory allocation for each element. So it is a relatively static array. I don't want to reinvent the wheel, so I ask if there is already something as a library or an addin etc. Any hints?

答案1

得分: 1

希望这对你有所帮助。

class StaticArray<T> {
    private var data: [T]
    private let capacity: Int
    
    init(capacity: Int) {
        self.capacity = capacity
        data = Array<T>(repeating: nil, count: capacity)
    }
    
    subscript(index: Int) -> T {
        get {
            return data[index]
        }
        set {
            data[index] = newValue
        }
    }
    
    func append(_ value: T) {
        // 在追加之前检查数组是否已满
        guard data.count < capacity else {
            return
        }
        data.append(value)
    }
    
    func sort() {
        data.sort()
    }
}
英文:

Hope this helps you.

    class StaticArray&lt;T&gt; {
    private var data: [T]
    private let capacity: Int
    
    init(capacity: Int) {
        self.capacity = capacity
        data = Array&lt;T&gt;(repeating: nil, count: capacity)
    }
    
    subscript(index: Int) -&gt; T {
        get {
            return data[index]
        }
        set {
            data[index] = newValue
        }
    }
    
    func append(_ value: T) {
        // Check if array is full before appending
        guard data.count &lt; capacity else {
            return
        }
        data.append(value)
    }
    
    func sort() {
        data.sort()
    }
}

huangapple
  • 本文由 发表于 2023年2月24日 00:31:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547668.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定