简体   繁体   English

ClosedRange 数组<Int>和反向收集<ClosedRange<Int> &gt;

[英]Array of ClosedRange<Int> and ReverseCollection<ClosedRange<Int>>

I can easily iterate through the elements of a closed range.我可以轻松地遍历封闭范围的元素。 Ditto for the elements of the reversed() of a closed range.同样适用于封闭范围的reversed()的元素。 However, these two constructs happen to have different types, such as ClosedRange<Int> for the former and ReverseCollection<ClosedRange<Int>> .然而,这两种结构碰巧有不同的类型,例如ClosedRange<Int>ReverseCollection<ClosedRange<Int>>

Suppose I need to have some kind of collection (eg, an array) including both ranges and reversed ranges: how would I go about it?假设我需要某种集合(例如,数组),包括范围和反向范围:我该怎么做?

Example:例子:

let aaa = 1...3
let bbb = (4...6).reversed()
let ranges = [aaa,bbb]  // heterogeneous collection literal could only be inferred of type '[Any]'
for range in ranges {
  for item in range {
    print(item)
  }
}

Simply declaring ranges to be of type [Sequence] or [Collection] does not work, because "Protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements".简单地将ranges声明为[Sequence][Collection]是行不通的,因为“协议‘序列’只能用作通用约束,因为它具有 Self 或相关的类型要求”。

You would need to convert all elements to the same type either Array or AnySequence , depending on your performance concerns.您需要将所有元素转换为相同类型的ArrayAnySequence ,具体取决于您的性能问题。 Array would create new storage but when the sequence is reversed may have better performance. Array会创建新的存储,但当顺序颠倒时可能会有更好的性能。 AnySequence merely forwards operations to its base class, thus depending on your sequence size, could be computationally complex. AnySequence仅将操作转发到其基类,因此根据您的序列大小,计算上可能很复杂。

let aaa = Array(1...3)
let bbb = Array((4...6).reversed())

let ranges = [aaa, bbb]
for range in ranges {
    for item in range {
        print(item)
    }
}

You can use AnySequence :您可以使用AnySequence

let aaa = AnySequence(1...3)
let bbb = AnySequence((4...6).reversed())
let ranges = [aaa, bbb] // ranges is [AnySequence<Int>]
for range in ranges {
  for item in range {
    print(item)
  }
}

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

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