[swift-evolution] Yet another fixed-size array spitball session

Alex Blewitt alblue at apple.com
Wed May 31 06:09:27 CDT 2017


> On 30 May 2017, at 16:27, David Sweeris via swift-evolution <swift-evolution at swift.org> wrote:
> 
> On May 30, 2017, at 03:25, Pavol Vaskovic <pali at pali.sk <mailto:pali at pali.sk>> wrote:
> 
>> On Tue, May 30, 2017 at 7:51 AM, David Sweeris <davesweeris at mac.com <mailto:davesweeris at mac.com>> wrote:
>> 
>> `(Int, Int, Int, Int)` isn't *that* horrible compared to "[Int x 4]", but would you want to replace "[Int8 x 10000]" with the multipage-long tuple equivalent?
>> 
>> 😳
>> It would be really helpful to my understanding, if you spoke about a practical use case. This reads as a contrived counterexample to me…
>> 
>> If your type really has 10 000 values in it, why does it have to be static, why doesn't normal Array fit the bill?
> 
> Sure, I meant it as an example of how unwieldy large tuples can be. Even medium ones, really. Tuples are great for bundling a few values, but much more than that any they become annoying to work with because there's no easy way to iterate through them. As a more realistic example, what if you want a stack-allocated 256-element buffer (which is a real possibility since statically-allocated C arrays are imported as tuples)? You have to manually keep track of i, because you have to hard-code which element you're addressing ("buf.0", "buf.1", etc), rather than being able to look it up directly from an index variable like, well, an array ("buf[i]").

The other issue is when you're importing an existing enum from a fixed size data structure which has a fixed array count:

// in include/*.h
#define MAX_ELEMENTS 100
typedef struct {
  size_t count;
  int elements[MAX_ELEMENTS];
} MyData

This gets imported into Swift as a 100-element tuple, which means you can't do elements[i] to look them up. And while a case statement will be hand-rollable, given that this is a compile-time value which could be changed in the future, it won't be safe.

You can end up with such unrolled loops (e.g. https://github.com/apple/swift-corelibs-foundation/blob/46b4e84a263d4fb657d84dfa4ca5b8fb4ed1f75f/Foundation/NSDecimal.swift#L1546-L1591 <https://github.com/apple/swift-corelibs-foundation/blob/46b4e84a263d4fb657d84dfa4ca5b8fb4ed1f75f/Foundation/NSDecimal.swift#L1546-L1591> ) but they're pretty unwieldy for something that should be a compile-time check.

It can be hacked with mirror, but well, it's a hack:

  subscript(index:Int) -> Int {
      let all = Mirror(reflecting:self.elements).children.map({$0.value as! Int})
      return all[index]
  }

Alex
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170531/d4264e3b/attachment.html>


More information about the swift-evolution mailing list