简体   繁体   English

如何从 ClosedRange.SubSequence 中删除 Slice<>?

[英]How do I remove the Slice<> from a ClosedRange.SubSequence?

I'm using the chunked method in Swift Algorithms .在 Swift Algorithms 中使用分块方法

When I work on a Range, it's pretty easy to handle the resulting type:当我在 Range 上工作时,处理结果类型非常容易:

let range: Range<Int> = 0..<5
let subRangesIntermediary: [Range<Int>.SubSequence] = range.chunked(on: { $0 / 2 })
assert(Range<Int>.SubSequence.self == Range<Int>.self)

let subRanges: [Range<Int>] = subRangesIntermediary
assert(subRanges == [0..<2, 2..<4, 4..<5])

That's because Range<Int>.SubSequence == Range<Int> so converting between the two is effortless.那是因为Range<Int>.SubSequence == Range<Int>所以两者之间的转换很容易。

When I try to do the same thing with ClosedRange , I run into problems:当我尝试用ClosedRange做同样的事情时,我遇到了问题:

let closedRange: ClosedRange<Int> = 0...4
let subClosedRangesIntermediary: [ClosedRange<Int>.SubSequence] = closedRange.chunked(on: { $0 / 2})
let subClosedRangesIntermediary2: [Slice<ClosedRange<Int>>] = subClosedRangesIntermediary
// assert(subClosedRangesIntermediary2 == [0...1, 2...3, 4...4]) // ❌ Binary operator '==' cannot be applied to operands of type '[Slice<ClosedRange<Int>>]' and 'ArraySlice<ClosedRange<Int>>'

That's because ClosedRange<Int>.SubSequence == Slice<ClosedRange<Int>> .那是因为ClosedRange<Int>.SubSequence == Slice<ClosedRange<Int>>

I'm looking to remove the Slice so that I'm left with an array of ClosedRange .我正在寻找删除 Slice 以便留下一组ClosedRange

I figured out a way to do it manually, but this looks like a lot of work:我想出了一种手动完成的方法,但这看起来需要做很多工作:

let subClosedRanges: [ClosedRange<Int>] = subClosedRangesIntermediary2.map {
  let start = closedRange[$0.startIndex]
  let end = closedRange[$0.index(before: $0.endIndex)]
  return start...end
}
assert(subClosedRanges == [0...1, 2...3, 4...4])

I was hoping there is a way to do something like the following instead:我希望有一种方法可以代替以下方法:

let subClosedRanges: [ClosedRange<Int>] = subClosedRangesIntermediary2.map { $0.valueInBase }

or:或者:

// Similar to how we can use Array(slice) on ArraySlice:
let subClosedRanges: [ClosedRange<Int>] = subClosedRangesIntermediary2.map { ClosedRange($0) }

I couldn't find anything like that for Slice .对于Slice ,我找不到类似的东西。

How do I convert a Slice<ClosedRange<T>> to a ClosedRange<T> ?如何将Slice<ClosedRange<T>>转换为ClosedRange<T>

Barring a more authoritative answer, here is a workaround:除非有更权威的答案,否则这里有一个解决方法:

extension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger {
  init(_ slice: Slice<Self>) {
    let lower = slice.base[slice.startIndex]
    let upper = slice.base[slice.index(before: slice.endIndex)]
    self.init(uncheckedBounds: (lower: lower, upper: upper))
  }
}

Usage:用法:

let subClosedRanges: [ClosedRange<Int>] = subClosedRangesIntermediary2.map { ClosedRange($0) }

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

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