How to make a generic specifiable associated type in Swift?

6 days ago 4
ARTICLE AD BOX

I'm trying to make a backport for integer generic parameters and a fixed size array that is stored on the stack (backporting InlineArray in short terms):

// Simplified, normally there is a way to get Int from the Num types. protocol SizeSpecifier { associatedtype Storage<X>: _Storage // errors } public enum Num1: SizeSpecifier { typealias Storage<X> = _StorageS1 // errors } public enum Num2: SizeSpecifier { typealias Storage<X> = _StorageS2 // errors } public enum Num3: SizeSpecifier { typealias Storage<X> = _StorageS3 // errors } // Storage shenanigans to store in stack protocol _Storage<T> { associatedtype T var cells: T { get set } } struct _StorageS1<Element>: _Storage { var cells: (Element) } struct _StorageS2<Element>: _Storage { var cells: (Element, Element) } struct _StorageS3<Element>: _Storage { var cells: (Element, Element, Element) } struct StackArray<Size: SizeSpecifier, Element> { var _storage: Size.Storage<Element> // errors }

The numbers have a internal storages associated with them, so for example if you choose number Num3, it will have storage for 3. But since it needs to be genericly constrained, somehow I need to support passing a generic through Num's without the Num itself being generic with a protocol conformance (Num1.Storage<Element> but through a protocol interface).

This array is meant to be stored in stack so I can't use Array since it's stored on heap. I also use the numbers as integer generic parameters so it can't have a generic specifier.

// Instead of let size: Int struct MyStruct<Size: SizeSpecifier> { // impl } let a: MyStruct<Num1</* what would be here if it was generic? */>>
Read Entire Article