[swift-evolution] Proposal to change subscript value type on Array and other collection types.
mich at el.cx
mich at el.cx
Thu Dec 17 10:55:32 CST 2015
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?
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.
More information about the swift-evolution