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

ilya ilya.nikokoshev at gmail.com
Thu Dec 17 14:33:35 CST 2015


> would it be sensible to make these UInt?

It's really nice to have one Int type to rule over all integers. This means
that a reasonable program can be written without casting.

> Which would be unnecessary if using the type system with UInt.

No, if subsript required UInt everyone would simply insert a cast, and -1
would still create problems as UInt.max.

On Thu, Dec 17, 2015 at 7:55 PM, 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/d2158ca3/attachment.html>


More information about the swift-evolution mailing list