[swift-evolution] [Pitch?] Way to declare a Swift Array that guarantees it can't be empty

Logan Shire logan.shire at gmail.com
Tue Aug 8 06:54:15 CDT 2017


You would have this guarantee with the fixed-size arrays currently being discussed. 
Perhaps this could be an amendment to that proposal - you could declare an array with bounds for its size.
Fixed-size arrays would be a subset of those where the upper and lower bounds are equal.
They could also offer non-opitional ‘first’ and ‘last’ properties, which, if the bounds are fixed,
could use the tuple .0, .1, etc syntax.

> This isn't a fully formed pitch, and maybe already discussed, but...
> 
> If we have have optionals and non-optionals, shouldn't we also have a way to declare that an Array never be empty? It seems like this would naturally lead to more elegant designs.
> 
> Here's a use-case:
> 
> struct Wavelet {
> var buff: [Double]
> var sign: Sign
> var peak:Double{
> returnbuff.find_max()! //<-- Yuck!
> }
> }
> 
> 
> In my app, I never want to create an empty "buff" here. If I could declare that the Array always contain at least 1 element, I wouldn't need to worry about a whole bunch of unwrapping elsewhere in my program. Native ability to do this would also be handy to store chunks of memory, too?
> 
> Would this be worthwhile?
> 
> 
> 
> 
> 
> 
> 


More information about the swift-evolution mailing list