Swift:切片startIndex始终为0

编程入门 行业动态 更新时间:2024-10-11 05:30:44
本文介绍了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确实有意义,因为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

本文发布于:2023-11-16 03:56:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1600775.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:切片   Swift   startIndex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!