If what you want is a fixed size array, and initialize it with nil
values, you can use an UnsafeMutableBufferPointer
, allocate memory for 64 nodes with it, and then read/write from/to the memory by subscripting the pointer type instance. This also has the benefit of avoiding checking if the memory must be reallocated, which Array
does. I would however be surprised if the compiler doesn't optimize that away for arrays that don't have any more calls to methods that may require resizing, other than at the creation site.
let count = 64
let sprites = UnsafeMutableBufferPointer<SKSpriteNode>.allocate(capacity: count)
for i in 0..<count {
sprites[i] = ...
}
for sprite in sprites {
print(sprite!)
}
sprites.deallocate()
This is however not very user friendly. So, let's make a wrapper!
class ConstantSizeArray<T>: ExpressibleByArrayLiteral {
typealias ArrayLiteralElement = T
private let memory: UnsafeMutableBufferPointer<T>
public var count: Int {
get {
return memory.count
}
}
private init(_ count: Int) {
memory = UnsafeMutableBufferPointer.allocate(capacity: count)
}
public convenience init(count: Int, repeating value: T) {
self.init(count)
memory.initialize(repeating: value)
}
public required convenience init(arrayLiteral: ArrayLiteralElement...) {
self.init(arrayLiteral.count)
memory.initialize(from: arrayLiteral)
}
deinit {
memory.deallocate()
}
public subscript(index: Int) -> T {
set(value) {
precondition((0...endIndex).contains(index))
memory[index] = value;
}
get {
precondition((0...endIndex).contains(index))
return memory[index]
}
}
}
extension ConstantSizeArray: MutableCollection {
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count - 1
}
func index(after i: Int) -> Int {
return i + 1;
}
}
Now, this is a class, and not a structure, so there's some reference counting overhead incurred here. You can change it to a struct
instead, but because Swift doesn't provide you with an ability to use copy initializers and deinit
on structures, you'll need a deallocation method (func release() { memory.deallocate() }
), and all copied instances of the structure will reference the same memory.
Now, this class may just be good enough. Its use is simple:
let sprites = ConstantSizeArray<SKSpriteNode?>(count: 64, repeating: nil)
for i in 0..<sprites.count {
sprite[i] = ...
}
for sprite in sprites {
print(sprite!)
}
For more protocols to implement conformance to, see the Array documentation (scroll to Relationships).