Swift:切片startIndex始终为0 [英] Swift: Slice startIndex always 0

查看:100
本文介绍了Swift:切片startIndex始终为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确实有意义,因为ArraystartIndex始终将是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆