简体   繁体   English

Swift:切片startIndex始终为0

[英]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). 我与Swift Slice发生冲突,认为firstIndex应该是该片段在源域中的第一个索引(不确定它还有什么用)。 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. 如果始终为0,则似乎完全没有用。

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 : 如果您浏览自动生成的Swift头文件(目前大多数文档都在其中),则会发现此内容描述了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 . 由于SliceArray式的,它有一定意义上startIndex将返回0 ,因为一个ArraystartIndex总是将是0 Further down, where it defines startIndex , you'll also see: 再往下,它在定义startIndex ,您还将看到:

/// 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 : 如果要在Slice查找第一个条目,只需使用: 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: 如果您需要在Slice开始的原始Array中找到索引,则可以执行以下操作:

if let startValue = s.first {
    let index = find(ary, startValue)
    /* ... do something with index ... */
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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