Fixed-length arrays are not yet supported. What does that actually mean? Not that you can't create an array of n many things — obviously you can just do let a = [ 1, 2, 3 ] to get an array of three Ints. It means simply that array size is not something that you can declare as type information.

If you want an array of nils, you'll first need an array of an optional type — [SKSpriteNode?], not [SKSpriteNode] — if you declare a variable of non-optional type, whether it's an array or a single value, it cannot be nil. (Also note that [SKSpriteNode?] is different from [SKSpriteNode]?... you want an array of optionals, not an optional array.)

Swift is very explicit by design about requiring that variables be initialized, because assumptions about the content of uninitialized references are one of the ways that programs in C (and some other languages) can become buggy. So, you need to explicitly ask for an [SKSpriteNode?] array that contains 64 nils:

Copyvar sprites = SKSpriteNode?
Answer from rickster on Stack Overflow
🌐
Gitbooks
victorqi.gitbooks.io › swift-algorithm › content › fixed_size_array.html
Fixed Size Array · Swift Algorithm
It will always be this size. If you need to fit more than 10 elements, you're out of luck... there is no room for it. To get an array that grows when it gets full you need to use a dynamic array object such as NSMutableArray in Objective-C or std::vector in C++, or a language like Swift whose ...
🌐
Medium
medium.com › @gvardikos › dynamic-array-size-in-swift-append-vs-reservecapacity-2ffdd41fef90
What is array reserveCapacity()
July 23, 2023 - In Swift, arrays have a dynamic size by default, meaning you can add or remove elements from an array after it has been created. So if you create an array of four elements, swift will allocate memory enough for the four elements.
🌐
TutorialKart
tutorialkart.com › swift-tutorial › get-array-size-count-in-swift
Get Array Size in Swift - count function - Examples
December 1, 2020 - To get the size of an array in Swift, use count function on the array.
Top answer
1 of 2
21

You can get the number of elements in an array simply with

let count = testArray.count

and the total number of bytes of its elements with

var arrayLength = testArray.count * sizeof(Int32)
// Swift 3:
var arrayLength = testArray.count * MemoryLayout<Int32>.size

sizeof is used with types and sizeofValue with values, so both

var arrayLength = sizeof([Int32])
var arrayLength = sizeofValue(testArray)

would compile. But that gives you the size of the struct Array, not the size of the element storage.

2 of 2
3

In Xcode 8 with Swift 3 beta 6 there is no function sizeof (). But if you want, you can define one for your needs. The good news are, that this new sizeof function works as expected with your array.

let bb: UInt8 = 1
let dd: Double = 1.23456

func sizeof <T> (_ : T.Type) -> Int
{
    return (MemoryLayout<T>.size)
}

func sizeof <T> (_ : T) -> Int
{
    return (MemoryLayout<T>.size)
}

func sizeof <T> (_ value : [T]) -> Int
{
    return (MemoryLayout<T>.size * value.count)
}

sizeof(UInt8.self)   // 1
sizeof(Bool.self)    // 1
sizeof(Double.self)  // 8
sizeof(dd)           // 8
sizeof(bb)           // 1

var testArray: [Int32] = [2000,400,5000,400]
var arrayLength = sizeof(testArray)  // 16

You need all versions of the sizeof function, to get the size of a variable and to get the correct size of a data-type and of an array.

If you only define the second function, then sizeof(UInt8.self) and sizeof(Bool.self) will result in "8". If you only define the first two functions, then sizeof(testArray) will result in "8".

🌐
Swift Forums
forums.swift.org › evolution › discussion
Approaches for fixed-size arrays - Discussion - Swift Forums
July 12, 2022 - We're looking into how best to give Swift the equivalent functionality of fixed-size arrays in C or other systems languages. Here are some directions I've been considering, and I'd love to hear the community's ideas and reactions: Tuples as fixed-size arrays This was the approach outlined in our most recent pitch on the subject: we already use homogeneous tuples to represent imported fixed-size array fields from C, and library developers sometimes reach for them manually (usually under duress) ...
Top answer
1 of 5
7

Nope, Swift doesn't come with this kind of array - which is similar to a View from a database - allowing you to peek the first N elements. Though for this both the view and it target should be reference types, which is not the case in Swift for arrays.

But enough blabbing around, you could quickly write a wrapper over an Array for fulfilling your needs:

/// 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)
    }
}

Since the struct conforms to Collection, you can easily pass it to code that knows only to work with arrays by transforming its contents into an array: Array(myLimitedArray).

2 of 5
3

simply count the elements of array before appending new element.

var array :[Int] = [1,2,3,4,5,6,7,8,9,10]

func insertIntoArray(_ value: Int, array: [Int]) -> [Int] {
    var arr = array
    if arr.count == 10 {
        arr.removeLast()
    }
    arr.append(value)
    return arr
}

array = insertIntoArray(11, array: array)
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › home › swift › swift arrays
Swift Arrays
April 4, 2015 - Swift puts strict checking which does not allow you to enter a wrong type in an array, even by mistake. If you assign a created array to a variable, then it is always mutable, which means you can change it by adding, removing, or changing its elements; but if you assign an array to a constant, then that array is immutable, and its size ...
🌐
Ole Begemann
oleb.net › blog › 2017 › 12 › fixed-size-arrays
A hack for fixed-size arrays in Swift – Ole Begemann
Swift doesn’t have a built-in type for fixed-size, stack-allocated arrays. The standard library uses code generation to work around this limitation for internal use.
🌐
Swift Forums
forums.swift.org › using swift
Fixed size array hacks - Using Swift - Swift Forums
January 23, 2020 - Swift doesn't have fixed size arrays, and I guess many of us have experimented with various workarounds. I thought it would be fun to share and discuss our ways around Swift's lack of fixed size arrays here.
🌐
DeveloperMemos
developermemos.com › posts › getting-size-list-array-swift
Getting the Size of a List/Array in Swift | DeveloperMemos
The simplest and most straightforward way to determine the size of an array or list in Swift is by using the built-in count property.
🌐
GitHub
gist.github.com › CTMacUser › cfffa526b971d0e1f3a079f53c6819bb
Swift proposal for fixed-size array types · GitHub
To maintain that advantage in Swift, the count lexically precedes the type. (Go uses a variant of the C array declaration syntax that also puts the count before the type.) [A previous version of this proposal used the colon as the separator between the bounds and element type. But a revised sized array literal syntax uses the semicolon, colon and comma as separators, using the semicolon to partition the bounds from the initialization terms.
🌐
Programiz
programiz.com › swift-programming › library › array › count
Swift Array count (With Examples)
// true because there are 10 elements on numbers if (numbers.count > 5) { print( "The array size is large") } else { print("The array size is small") }
🌐
Apple Developer
developer.apple.com › documentation › swift › array › capacity
capacity | Apple Developer Documentation
The total number of elements that the array can contain without allocating new storage.
🌐
TutorialKart
tutorialkart.com › swift-tutorial › how-to-create-an-array-of-specific-size-in-swift
How to Create an Array of specific Size in Swift?
March 6, 2021 - To create an array of specific size in Swift, use Array initialiser syntax and pass this specific size. We also need to pass the default value for these elements in the Array. Array(repeating: defaultValue, count: specificSize)