简体   繁体   中英

Swift: Slice startIndex always 0

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.

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 ... */
}

在Swift 2中已修复。如果对范围为2...5的数组进行切片,切片的startIndex将为2。非常酷。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM