有没有一种方法可以在 swift 中限制数组大小,以便在数组已满时向其追加元素时,它不会追加?
我知道这可以通过编程方式完成。想知道 swift 是否对此有内置处理。
例如:
数组 -> 大小为 10 的数组
array.append(1)
.
.
.
array.append(10)
array.append(11) // Doesn't do anything?
array.insert(0, pos: 0)
用例:将最后一个元素推出数组以为新元素腾出空间?
编辑 - 最后一行是主要用例。
最佳答案
不,Swift 没有提供这种数组——类似于数据库中的 View ——允许您查看前 N 个元素。虽然为此, View 和它的目标都应该是引用类型,但在 Swift 中数组不是这种情况。
但是废话不多说了,您可以快速在 Array
上编写一个包装器来满足您的需求:
/// an array-like struct that has a fixed maximum capacity
/// any element over the maximum allowed size gets discarded
struct LimitedArray<T> {
private(set) var storage: [T] = []
public let maxSize: Int
/// creates an empty array
public init(maxSize: Int) {
self.maxSize = maxSize
}
/// takes the max N elements from the given collection
public init<S: Sequence>(from other: S, maxSize: Int) where S.Element == T {
self.maxSize = maxSize
storage = Array(other.prefix(maxSize))
}
/// adds a new item to the array, does nothing if the array has reached its maximum capacity
/// returns a bool indicated the operation success
@discardableResult public mutating func append(_ item: T) -> Bool {
if storage.count < maxSize {
storage.append(item)
return true
} else {
return false
}
}
/// inserts an item at the specified position. if this would result in
/// the array exceeding its maxSize, the extra element are dropped
public mutating func insert(_ item: T, at index: Int) {
storage.insert(item, at: index)
if storage.count > maxSize {
storage.remove(at: maxSize)
}
}
// add here other methods you might need
}
// let's benefit all the awesome operations like map, flatMap, reduce, filter, etc
extension LimitedArray: MutableCollection {
public var startIndex: Int { return storage.startIndex }
public var endIndex: Int { return storage.endIndex }
public subscript(_ index: Int) -> T {
get { return storage[index] }
set { storage[index] = newValue }
}
public func index(after i: Int) -> Int {
return storage.index(after: i)
}
}
由于该结构符合 Collection
,您可以轻松地将其传递给只知道使用数组的代码,方法是将其内容转换为数组:Array(myLimitedArray)
.
关于arrays - 快速限制数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49144910/