数组范围迅速

编程入门 行业动态 更新时间:2024-10-14 06:25:58
本文介绍了数组范围迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下python代码的快速等效之处是什么?

What could be the swift equivalent of following python code ?

array =[ "a", "b", "c"] print(array[1:])

(上面的语句打印从第一个索引到数组末尾的每个元素.输出 ['b','c'])

( Above statement prints every element from first index upto end of array. Output ['b', 'c'])

修改 有没有一种方法可以使用array.count来完成?由于array.count是多余的,如果我说要从第二个位置开始每个元素

Edit Is there a way where this could be done with out using array.count ? Since the array.count is redundant if I say want every element from second position

推荐答案

您可以通过以下方式实现所需的目标:

You can achieve what you're looking for in the following way:

1..创建一个自定义结构来存储开始和结束索引.如果 startIndex 或 endIndex 为 nil ,这将表示该范围沿该方向无限扩展.

1. Create a custom struct to store a start and end index. If startIndex or endIndex is nil this will be taken to mean the range extends infinitely in that direction.

struct UnboundedRange<Index> { var startIndex, endIndex: Index? // Providing these initialisers prevents both `startIndex` and `endIndex` being `nil`. init(start: Index) { self.startIndex = start } init(end: Index) { self.endIndex = end } }

2..在我的选择中,定义运算符以创建 BoundedRange ,因为必须使用初始化程序会导致一些相当难看的代码.

2. Define operators to create an BoundedRange as having to use the initialisers will lead to some quite unsightly code, in my option.

postfix operator ... {} prefix operator ... {} postfix func ... <Index> (startIndex: Index) -> UnboundedRange<Index> { return UnboundedRange(start: startIndex) } prefix func ... <Index> (endIndex: Index) -> UnboundedRange<Index> { return UnboundedRange(end: endIndex) }

一些用法示例:

1... // An UnboundedRange<Int> that extends from 1 to infinity. ...10 // An UnboundedRange<Int> that extends from minus infinity to 10.

3..扩展 CollectionType ,以便它可以处理 UnboundedRange s.

3. Extend the CollectionType so it can handle UnboundedRanges.

extension CollectionType { subscript(subrange: UnboundedRange<Index>) -> SubSequence { let start = subrange.startIndex ?? self.startIndex let end = subrange.endIndex?.advancedBy(1) ?? self.endIndex return self[start..<end] } }

4..要在给定的示例中使用它,请执行以下操作:

4. To use this in your given example:

let array = ["a", "b", "c"] array[1...] // Returns ["b", "c"] array[...1] // Returns ["a", "b"]

更多推荐

数组范围迅速

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

发布评论

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

>www.elefans.com

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