[swift] How to create a fixed-size array of objects

In Swift, I am trying to create an array of 64 SKSpriteNode. I want first to initialize it empty, then I would put Sprites in the first 16 cells, and the last 16 cells (simulating an chess game).

From what I understood in the doc, I would have expect something like:

var sprites = SKSpriteNode()[64];

or

var sprites4 : SKSpriteNode[64];

But it doesn't work. In the second case, I get an error saying: "Fixed-length arrays are not yet supported". Can that be real? To me that sounds like a basic feature. I need to access the element directly by their index.

This question is related to swift ios8 xcode6

The answer is


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).


This question has already been answered, but for some extra information at the time of Swift 4:

In case of performance, you should reserve memory for the array, in case of dynamically creating it, such as adding elements with Array.append().

var array = [SKSpriteNode]()
array.reserveCapacity(64)

for _ in 0..<64 {
    array.append(SKSpriteNode())
}

If you know the minimum amount of elements you'll add to it, but not the maximum amount, you should rather use array.reserveCapacity(minimumCapacity: 64).


The best you are going to be able to do for now is create an array with an initial count repeating nil:

var sprites = [SKSpriteNode?](count: 64, repeatedValue: nil)

You can then fill in whatever values you want.


In Swift 3.0 :

var sprites = [SKSpriteNode?](repeating: nil, count: 64)

Declare an empty SKSpriteNode, so there won't be needing for unwraping

var sprites = [SKSpriteNode](count: 64, repeatedValue: SKSpriteNode())

For now, semantically closest one would be a tuple with fixed number of elements.

typealias buffer = (
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
    SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode)

But this is (1) very uncomfortable to use and (2) memory layout is undefined. (at least unknown to me)


One thing you could do would be to create a dictionary. Might be a little sloppy considering your looking for 64 elements but it gets the job done. Im not sure if its the "preferred way" to do it but it worked for me using an array of structs.

var tasks = [0:[forTasks](),1:[forTasks](),2:[forTasks](),3:[forTasks](),4:[forTasks](),5:[forTasks](),6:[forTasks]()]

Swift 4

You can somewhat think about it as array of object vs. array of references.

  • [SKSpriteNode] must contain actual objects
  • [SKSpriteNode?] can contain either references to objects, or nil

Examples

  1. Creating an array with 64 default SKSpriteNode:

    var sprites = [SKSpriteNode](repeatElement(SKSpriteNode(texture: nil),
                                               count: 64))
    
  2. Creating an array with 64 empty slots (a.k.a optionals):

    var optionalSprites = [SKSpriteNode?](repeatElement(nil,
                                          count: 64))
    
  3. Converting an array of optionals into an array of objects (collapsing [SKSpriteNode?] into [SKSpriteNode]):

    let flatSprites = optionalSprites.flatMap { $0 }
    

    The count of the resulting flatSprites depends on the count of objects in optionalSprites: empty optionals will be ignored, i.e. skipped.


Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to ios8

Is there any way to show a countdown on the lockscreen of iphone? How to display an activity indicator with text on iOS 8 with Swift? How to call gesture tap on UIView programmatically in swift Changing the Status Bar Color for specific ViewControllers using Swift in iOS8 Can I set the cookies to be used by a WKWebView? UIAlertController custom font, size, color How to force view controller orientation in iOS 8? How to get textLabel of selected row in swift? Launch Image does not show up in my iOS App NavigationBar bar, tint, and title text color in iOS 8

Examples related to xcode6

'Framework not found' in Xcode No suitable records were found verify your bundle identifier is correct unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard Move a view up only when the keyboard covers an input field My prerelease app has been "processing" for over a week in iTunes Connect, what gives? Programmatically navigate to another view controller/scene Changing the Status Bar Color for specific ViewControllers using Swift in iOS8 Change tab bar item selected color in a storyboard How do I change UIView Size? How to get textLabel of selected row in swift?