Swift:切片startIndex始终为0 [英] Swift: Slice startIndex always 0
问题描述
我与Swift Slice发生冲突,以为firstIndex应该是切片的第一个索引,在源域中(不确定它还有什么用).显然不是这样:
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)
这看起来像是个错误吗?如果始终为0,则似乎完全没有用.
Does this seem like a bug? If it's always 0, it seems totally useless.
推荐答案
如果您深入研究自动生成的Swift头文件(目前大多数文档都在此文件中),则会发现此内容描述了Slice
:
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`.
由于Slice
类似于Array
,因此startIndex
将返回0
确实有意义,因为Array
的startIndex
始终将是0
.在其下定义startIndex
的位置,您还将看到:
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 }
如果要查找Slice
中的第一个条目,只需使用:s.first
:
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 }
如果您需要在Slice
起始的原始Array
中找到索引,则可以执行以下操作:
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:切片startIndex始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!