Reputation: 9039
I ran afoul of Swift Slice, thinking that firstIndex should be the first index of the slice, in the domain of the source (not sure what else it's useful for). Evidently this is not the case:
let ary = map(1...100) { i in i }
let s:Slice<Int> = ary[10..<20]
s.startIndex // 0
ary[10..<20].startIndex // 0
(10..<20).startIndex // 10 (half-open interval generated from a range, presumably)
Does this seem like a bug? If it's always 0, it seems totally useless.
Upvotes: 0
Views: 1140
Reputation: 42325
NOTE: The following applies to Swift 2 or earlier. The behavior has changed since Swift 2.
If you dig around in the auto-generated Swift header file (where it seems most of the documentation is at the moment), you'll find this describing Slice
:
/// The `Array`-like type that represents a sub-sequence of any
/// `Array`, `ContiguousArray`, or other `Slice`.
Since Slice
is Array
-like, it does make sense that startIndex
would be returning 0
since an Array
's startIndex
is always going to be 0
. Further down, where it defines startIndex
, you'll also see:
/// Always zero, which is the index of the first element when non-empty.
var startIndex: Int { get }
If you're looking for the first entry in the Slice
, just use: s.first
:
/// The first element, or `nil` if the array is empty
var first: T? { get }
If you need to find the index in the original Array
that where the Slice
starts, you can do something like this:
if let startValue = s.first {
let index = find(ary, startValue)
/* ... do something with index ... */
}
Upvotes: 2
Reputation: 18493
This is fixed in Swift 2. If you slice an array with a range of 2...5
, the startIndex of the slice will be 2. Very cool.
Upvotes: 1