Reputation: 6018
The documentation about IndexSet
said:
The range of valid integer values is
0..<INT_MAX-1
. Anything outside this range is an error.
But this code works fine:
let indexSet = IndexSet(integer: -1)
And if we try with -2
, it will produce a crash as expected.
Why this happened? Is it a bug or i missed something?
Tested on Xcode 9.4.1, Swift 4.1.
Upvotes: 0
Views: 340
Reputation: 18591
This is a bug. It comes from the fact that the initializer of an IndexSet
is not failable. Here is the initializer as defined in the standard library:
/// Initialize an `IndexSet` with a single integer.
public init(integer: Element) {
_handle = _MutablePairHandle(NSIndexSet(index: integer), copying: false)
}
Using unsigned integers should have been the way to go in order to be consistent with the definition:
The range of valid integer values is
0..<INT_MAX-1
. Anything outside this range is an error.
You could have this extension to be safe:
extension IndexSet {
public init(unsignedInt: UInt) {
self = IndexSet(integer: Int(unsignedInt))
}
}
So when you try to initialize an IndexSet with a negative integer, it will give you a proper error message:
IndexSet(unsignedInt: -1) //Negative integer '-1' overflows when stored into unsigned type 'UInt'
Upvotes: 2