以下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"]更多推荐
数组范围迅速
发布评论