Swift: Slice startIndex always 0

时光怂恿深爱的人放手 提交于 2019-12-12 02:56:06

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/26152604/swift-slice-startindex-always-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!