[swift-evolution] Proposal to change subscript value type on Array and other collection types.

Donnacha Oisín Kidney oisin.kidney at gmail.com
Thu Dec 17 10:59:08 CST 2015


There’s a good discussion of this here <https://devforums.apple.com/thread/263668>.

> On 17 Dec 2015, at 16:55, Michael Armstrong via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hi,
> 
> My first post to this list so apologies if its not in the correct format or irrelevant / wrong :) Its quite simple, so i'm under the impression that perhaps there is already a very good reason why the below behaviour is on purpose, if this is the case i'd love to learn why, so view it as a proposal / question.
> 
> When accessing Array's in Swift (and potentially other types) a Int (signed) is expected, as Array can't have a negative bounds in Swift (as far as i'm aware) would it be sensible to make these UInt? therefor removing the need for tests etc and guarding around negative integers?
> 
> For Example:
> 
>     let someArray = ["a", "b", "c"]
>     print(someArray.count.dynamicType) // Int
> 
>     let someIndex = 1
>     print(someArray[someIndex]) // b
> 
>     let anotherIndex : UInt = 1
>     print(someArray[anotherIndex]) // cannot subscript a value of type '[String]' with an index of type 'UInt'
> 
>     let invalidIndex = -1
>     print(someArray[invalidIndex]) //  Darwin: EXC_BAD_INSTRUCTION / Linux REPL: Error running code: unknown error code 132.
> 
>     print (invalidIndex.dynamicType) // Int
> 
>     If Array took a UInt, the line 'print(someArray[invalidIndex])' would fail at COMPILE time rather than RUNTIME.
> 
> 
> Looking at the Swift source there are things like
> 
>    _sanityCheck(count >= 0)
> 
> Which would be unnecessary if using the type system with UInt.
> 
> I'm aware that almost everyone bounds checks Array's before access etc, however is there a reason someone can explain for not using a 'UInt' in these circumstances for 'Array' and other collection types.
> 
> Thanks,
> 
> Michael
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


More information about the swift-evolution mailing list