Swift 3 中的 ClosedRange 和数组下标

ClosedRange and array subscripting in Swift 3

我正在将我的代码转换为 Swift3,只剩下 3 个构建时错误,其中 2 个与我不了解范围现在的工作原理有关。例如,我有:

func shuffle( _ tenseArray: [ Tense ], ...

    var indices = [ Int ]()
    for tense in tenseArray {
        if let aRange = tenseRange[ tense ] { 
            indices.append( aRange )
        }
    }

其中 Tense 是一个类似于以下内容的枚举:

 enum Tense: String {
    case IndicativePresent = "Indicative Present"
    case IndicativePreterite = "Indicative Preterite"
    case IndicativeImperfect = "Indicative Imperfect"
    ...

tenseRange定义为:

var tenseRange: [ Tense : ClosedRange<Int> ] = [:] // maps Tense enums to ranges of tense indices

并且是这样填充的:

tenseRange[ Tense.IndicativePresent ] = ( 11 ... 16 )
tenseRange[ Tense.IndicativePreterite ] = ( 17 ... 22 )
tenseRange[ Tense.IndicativeImperfect ] = ( 23 ... 28 )
...

对于 func shuffle

中的行
indices.append( aRange )

我收到错误 无法使用 'CountableRange' 类型的索引下标“[Int]”类型的值。我真的很想将这些范围转换为整数以用于数组的索引,就像我之前在 Swift 中所做的那样,但我似乎无法弄清楚如何。有什么想法吗?

提前致谢!

您将 indices 声明为 IntArray,因此您不能将 append(_:) 用于 ClosedRange<Int>

因此,我假设您想将 ClosedRange 中的所有值附加到 indices

在这种情况下,您可能需要使用 append(contentsOf:),而不是 append(_:)

Array

...

func append(Element)

Adds a new element at the end of the array.

...

func append(contentsOf: C)

Adds the elements of a collection to the end of the array.

func append(contentsOf: S)

Adds the elements of a sequence to the end of the array.

不幸的是,在 Swift 3 中,CountableRange<T> 既不是集合也不是序列。

但是Swift3引入了一个新的Range家族类型,CountableClosedRange<T>CountableRange<T>,它们都是Collection。闭域运算符 ... 的结果类型在特定上下文中可以是 CountableClosedRange<T>

        indices.append(contentsOf: aRange.lowerBound...aRange.upperBound)

否则,您可以将 tenseRange 的值声明为 CountableClosedRange<Int>

var tenseRange: [ Tense : CountableClosedRange<Int> ] = [:]