# Vector, a fixed-size array

**URL:** <https://forums.swift.org/t/vector-a-fixed-size-array/75264>\
**Category:** Pitches\
**Tags:** array\
**Created:** [October 10, 2024, 1:18am UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264 "2024-10-10T01:18:30Z")\
**Posts on this page:** 20\
**Page:** 3

<div class="post-metadata">

**Author:** ![fclout](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/fclout/32/36155_2.png) [@fclout](https://forums.swift.org/u/fclout)\
**Post date:** [October 10, 2024, 3:35pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/42 "2024-10-10T15:35:52Z")

</div>

The proposal includes a `swapAt` function that updates an element and returns the old one. This method does not exist on `Array` and instead we have a global `swap` function to do it. Is this best thought of as a "swap" operation? I hate to be bringing up new naming concerns, but since it doesn't exchange the contents of two objects, I was wondering if there are alternatives considered. `replace(at:with:)`? There has to be more.

Less actionable now, but I think the `ExpressibleByVectorLiteral` section doesn't go far enough. I think that `ExpressibleByVectorLiteral` should replace `ExpressibleByArrayLiteral` because array literals, by definition, always have a fixed size.

---

<div class="post-metadata">

**Author:** ![allevato](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/allevato/32/385_2.png) [@allevato](https://forums.swift.org/u/allevato)\
**Post date:** [October 10, 2024, 3:36pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/43 "2024-10-10T15:36:07Z")

</div>

> [@Alejandro](#):
>
> ### Literal Initialization
> 
> [...] A stack allocated vector using a vector literal will do in place initialization  
> of each element at its stack slot.

I didn't see it mentioned explicitly, but can you confirm whether global/static data will then also be represented as constant data in the binary if the values themselves are literals and that no other initialization cost would occur when accessing it?

A major problem Swift has today is that something like `static let myArray: [UInt8] = [...]` has unpredictable codegen; depending on whether you're compiling with optimization or not, and depending on the size of the array, it might get outlined to constant data or it might generate a sequence of instructions to initialize a backing array at runtime. This makes it extremely difficult to write algorithms that use tabular data while guaranteeing good performance. While it would be nice if `Array` addressed this, if `Vector` does then it at least gives us another path to explore.

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [October 10, 2024, 3:39pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/44 "2024-10-10T15:39:02Z")

</div>

The `swapAt(_:with:)` variant that takes one index doesn't do anything that the global `swap` and `exchange` functions can't do, and doesn't need to exist.

---

<div class="post-metadata">

**Author:** ![Slava\_Pestov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slava_pestov/32/30204_2.png) [@Slava\_Pestov](https://forums.swift.org/u/Slava_Pestov)\
**Post date:** [October 10, 2024, 3:54pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/45 "2024-10-10T15:54:53Z")

</div>

> [@allevato](#):
>
> A major problem Swift has today is that something like `static let myArray: [UInt8] = [...]` has unpredictable codegen; depending on whether you're compiling with optimization or not, and depending on the size of the array, it might get outlined to constant data or it might generate a sequence of instructions to initialize a backing array at runtime

It shouldn’t depend on the size of the array, because the optimization is most profitable for large arrays. If you find a reproducer please file a bug. It might even make sense to promote it to a mandatory optimization since I don’t think it impacts debug info, but that depends on how expensive the transformation is. But again if it doesn’t scale well that’s something that ought to be addressed eventually. The same optimization should apply to fixed size arrays too, I can’t imagine a situation where we cannot make this guarantee, assuming the element type is known.

---

<div class="post-metadata">

**Author:** ![jcarrillo7](https://avatars.discourse-cdn.com/v4/letter/j/8c91f0/32.png) [@jcarrillo7](https://forums.swift.org/u/jcarrillo7)\
**Post date:** [October 10, 2024, 3:59pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/46 "2024-10-10T15:59:33Z")

</div>

Long time observer just chiming in but I actually like the name Vector and I think it makes sense for this type given what it is. My educational background in CS started with languages that called the “growable” container an Array and then moved to languages like C that called the fixed size one array and I always found that confusing.

That said I’ll note some interesting tidbits: the [Wikipedia page for array](https://en.wikipedia.org/wiki/Array_(data_structure)) mentions (in passing)

> In some cases the term "vector" is used in computing to refer to an array, although [tuples](https://en.wikipedia.org/api/rest_v1/page/mobile-html/Tuple) rather than [vectors](https://en.wikipedia.org/api/rest_v1/page/mobile-html/Vector_space) are the more mathematically correct equivalent.

Even given that I’d still rather it be called Vector (especially since we already have something called Array and that ship has sailed) and prefer that over something like FixedSizeArray (which to me implies some kind of sub-typing is going on).

---

<div class="post-metadata">

**Author:** ![fclout](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/fclout/32/36155_2.png) [@fclout](https://forums.swift.org/u/fclout)\
**Post date:** [October 10, 2024, 4:00pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/47 "2024-10-10T16:00:59Z")

</div>

Another thing I wanted to throw out there is that we can make the transition from tuples to Vector easier by allowing types to respond to numeric fields, `@dynamicMemberLookup`-style. If you could write `vector.1` and that was the same as `vector[1]`, most code bases would be instantly compatible with the change.

---

<div class="post-metadata">

**Author:** ![allevato](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/allevato/32/385_2.png) [@allevato](https://forums.swift.org/u/allevato)\
**Post date:** [October 10, 2024, 4:21pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/48 "2024-10-10T16:21:32Z")

</div>

> [@Slava\_Pestov](#):
>
> It shouldn’t depend on the size of the array, because the optimization is most profitable for large arrays. If you find a reproducer please file a bug.

Filed [#76953](https://github.com/swiftlang/swift/issues/76953) (similar to [this post](https://forums.swift.org/t/consistency-of-the-objectoutliner-siloptimizer-pass/53764) from a few years ago, which unfortunately got little traffic). Even a trivial 10-element global array codegens move instructions without `-O`. ☹

> [@](#):
>
> It might even make sense to promote it to a mandatory optimization since I don’t think it impacts debug info, but that depends on how expensive the transformation is.

At a minimum, I hope that simple static arrays of numeric constants could be done this way without it being expensive; my own use cases aren't embedded programming but it feels like this would be a major need there to embed data without incurring major codegen/runtime costs.

---

<div class="post-metadata">

**Author:** ![filip-sakel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/filip-sakel/32/8697_2.png) [@filip-sakel](https://forums.swift.org/u/filip-sakel)\
**Post date:** [October 10, 2024, 4:44pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/49 "2024-10-10T16:44:39Z")

</div>

Would there be a way to use a runtime integer to initialize this fixed-size array? IIRC, generic int parameters need to be initialized with a compile-time constant. If not, what would be a good way to replace withUnsafeTemporaryAllocation with a safer construct?

---

<div class="post-metadata">

**Author:** ![Slava\_Pestov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slava_pestov/32/30204_2.png) [@Slava\_Pestov](https://forums.swift.org/u/Slava_Pestov)\
**Post date:** [October 10, 2024, 4:57pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/50 "2024-10-10T16:57:44Z")

</div>

> [@filip-sakel](#):
>
> Would there be a way to use a runtime integer to initialize this fixed-size array?

In this model an ordinary value of type Int is an existential so you could imagine passing an Int value as an integer parameter type by “opening” it, just like we do with `any P`; it would have the same limitations and guarantees.

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [October 10, 2024, 5:09pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/51 "2024-10-10T17:09:14Z")

</div>

> [@filip-sakel](#):
>
> IIRC, generic int parameters need to be initialized with a compile-time constant.

This is not an inherent requirement, since integer parameters are not required to be specialized any more than other generic parameters are. We should eventually be able to use a constant integer value as a local generic parameter, analogously to how existential values can be opened to use their dynamic type as a generic type parameter.

---

<div class="post-metadata">

**Author:** ![Alejandro](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alejandro/32/46197_2.png) [@Alejandro](https://forums.swift.org/u/Alejandro)\
**Post date:** [October 10, 2024, 5:10pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/52 "2024-10-10T17:10:15Z")

</div>

> [@saagarjha](#):
>
> Do we actually truly intend to guarantee all of these things? Can I take the address of such an object directly and muck around with it?

Yes, a `Vector` will always have the layout of `Count` elements with `Element.stride * Count`.

> [@saagarjha](#):
>
> Is this type never going to be copy-on-write?

This type is just a regular value type like `Int` and `Double`. You can explicitly copy it (if it's copyable) and that will be an immediate eager copy and mutations will occur on whatever owned copy you have.

> [@saagarjha](#):
>
> Will we never add metadata to it?

All types in Swift have metadata, so by extension this type will come with new metadata.

> [@saagarjha](#):
>
> This seems like a reasonable extension but actually has subtle nuance. An imported fixed-size (such as one similar the very one you mention) can be partially initialized. This type cannot be as far as I can tell. That is fine if you only do member-wise accesses to the data that is initialized, but the new type lets people iterate over the collection and read uninitialized data. I would feel better if you explicitly addressed the rules around this. One example you may wish to pair with that is the actual code to read out `sectname` and `segname` using this new interface ;)

We technically already have this problem with tuples however. Tuples cannot have uninitialized elements, yet we import potentially uninitialized C arrays into fully initialized tuples in Swift. This pitch isn't making any current behavior better or worse with regards to imported C array initialization.

> [@saagarjha](#):
>
> Partially addressed above but want to repeat in this context: is this type ABI compatible with a tuple? Is there a potential migration path here for people who are already using tuples?

This type does not have the ABI layout as tuples as tuples omit padding on the last element while this type preserves such padding.

---

<div class="post-metadata">

**Author:** ![j-f1](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/j-f1/32/12287_2.png) [@j-f1](https://forums.swift.org/u/j-f1)\
**Post date:** [October 10, 2024, 5:14pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/53 "2024-10-10T17:14:13Z")

</div>

> [@Slava\_Pestov](#):
>
> there’s certainly a good case that Vector (or FixedArray or whatever) should actually conditionally conform to AdditiveArithmetic (and maybe other protocols) if its element type does, because there is only one possible implementation of this conformance that works.

There’s certainly the elementwise implementation of this conformance, but given `Vector` is sort of like an array, wouldn’t you expect `[1, 2] + [3, 4] == [1, 2, 3, 4] as Vector` to be true?

> [@fclout](#):
>
> Less actionable now, but I think the `ExpressibleByVectorLiteral` section doesn't go far enough. I think that `ExpressibleByVectorLiteral` should replace `ExpressibleByArrayLiteral` because array literals, by definition, always have a fixed size.

If we do this, I feel like there should be a way for conforming types to be allowed to constrain their initializer to a fixed set of count(s). For example, `[1, 2, 3] as SIMD2<Int>` should be a compile-time, not runtime, error.

---

<div class="post-metadata">

**Author:** ![Datagram](https://avatars.discourse-cdn.com/v4/letter/d/7cd45c/32.png) [@Datagram](https://forums.swift.org/u/Datagram)\
**Post date:** [October 10, 2024, 5:19pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/54 "2024-10-10T17:19:44Z")

</div>

Woww what fantastic work! The wait will have been worth it.

I'm really looking forward to experimenting with the new Vector type.

Thanks !

---

<div class="post-metadata">

**Author:** ![rauhul](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rauhul/32/35207_2.png) [@rauhul](https://forums.swift.org/u/rauhul)\
**Post date:** [October 10, 2024, 5:25pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/55 "2024-10-10T17:25:27Z")

</div>

I don't have a specific issue with the name `Vector` but I am curious what a future Fixed _Capacity_ Array might be named, and similarly what names we might give other fixed collections, like `{Stack|Queue|RingBuffer}<let Capacity: Int, Element>` etc...

To add to the madness, what if we allowed for type overloading by generic parameter name? I don't necessarily think this is a great idea but maybe it's a direction thinking about. `Array<Capacity:> != Array<Count:> != Array`

---

<div class="post-metadata">

**Author:** ![nnnnnnnn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nnnnnnnn/32/264_2.png) [@nnnnnnnn](https://forums.swift.org/u/nnnnnnnn)\
**Post date:** [October 10, 2024, 5:56pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/56 "2024-10-10T17:56:09Z")

</div>

This is great! Would you consider providing a way to create a `Vector` parallel to the `Array(unsafeUnitializedCapacity:initializingWith:)` initializer? Sometimes it's useful to initialize out of order, as long as you can still guarantee the total number of elements.

Since it wouldn't have an integer parameter, it might need to be a static method:

```swift
extension Vector {
    static func unsafeUninitialized(initializingWith: (UnsafeBufferPointer<Element>) throws -> Void) rethrows -> Self
}

```

---

<div class="post-metadata">

**Author:** ![clark](https://avatars.discourse-cdn.com/v4/letter/c/6de8d8/32.png) [@clark](https://forums.swift.org/u/clark)\
**Post date:** [October 10, 2024, 6:07pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/57 "2024-10-10T18:07:41Z")

</div>

While I fully support the long overdue and much-needed proposal, I can't help but chime in on the least important aspect, the name.

In mathematical usage, a 'vector' is just a thing with certain algebraic properties (namely, addition and scalar multiplication). It has nothing to do with being a fixed-length list of elements.

Naming this new type a vector wouldn't right any past wrongs, but only add to the confusion.

---

<div class="post-metadata">

**Author:** ![Max\_Desiatov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/max_desiatov/32/20654_2.png) [@Max\_Desiatov](https://forums.swift.org/u/Max_Desiatov)\
**Post date:** [October 10, 2024, 6:22pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/58 "2024-10-10T18:22:24Z")

</div>

Strong +1 for the pitch. It is sorely needed for Embedded Swift.

As for naming, I think `FixedSizeArray` makes as much sense for this type, as `DynamicSizeUnicodeCharactersCollection` does for a string type, i.e. not at all.

Since const generics are a special case of dependent types, in dependent types `Vector` is a well-established term of art. For Swift not to follow that would be disappointing.

In fact, only alternative I would consider is `Vec`, in the same way we've chosen `Int` instead of `Integer`. I realize for collections and sequences we're not consistent and are sticking to verbose spelling, like `String` instead of `Str` and `Dictionary` instead of `Dict`. Thus `Vector` it is.

---

<div class="post-metadata">

**Author:** ![Datagram](https://avatars.discourse-cdn.com/v4/letter/d/7cd45c/32.png) [@Datagram](https://forums.swift.org/u/Datagram)\
**Post date:** [October 10, 2024, 7:03pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/59 "2024-10-10T19:03:01Z")

</div>

As for naming, Vector doesn't worry me much since different languages ​​already have different names for dynamically sized arrays. In C# it's List, C++ it's std::vector and Swift it's Array. So for a fixed size array, Vector is no more confusing than this already existing confusion ;)

However, during the first debate about fixed-size arrays in Swift in 2022, the name FixedArray was proposed and I really liked it.

---

<div class="post-metadata">

**Author:** ![rvsrvs](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rvsrvs/32/5270_2.png) [@rvsrvs](https://forums.swift.org/u/rvsrvs)\
**Post date:** [October 10, 2024, 7:24pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/60 "2024-10-10T19:24:57Z")

</div>

What's the feature flag this is behind? and is a nightly build the correct thing to try it with?

---

<div class="post-metadata">

**Author:** ![seriyvolk83](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/seriyvolk83/32/37624_2.png) [@seriyvolk83](https://forums.swift.org/u/seriyvolk83)\
**Post date:** [October 10, 2024, 7:26pm UTC](https://forums.swift.org/t/vector-a-fixed-size-array/75264/61 "2024-10-10T19:26:41Z")

</div>

A better (sugar-like) syntax for `Vector` as a parameter would be:

```swift
func complexAlgorthim(values: Int...4) {
...
}

```

[Previous page](https://forums.swift.org/t/vector-a-fixed-size-array/75264.md?page=2)

[Next page](https://forums.swift.org/t/vector-a-fixed-size-array/75264.md?page=4)
