使用范围从 swift2 迁移到 swift3 的问题

Problems with migration from swift2 to swift3 with ranges

我有字符串并确定索引的范围。稍后我将需要 .last .count 这些范围。我应该如何初始化字符串的范围才能获得这些范围的功能 .last .count (这在 swift2 中很明显,但在 swift3 中不是)?

例如,我经常在我的 swift2 代码中使用 .count 作为字符串范围,就像这样

var str = "Hello, playground"

let myRange = str.rangeOfString("Hello")

let myCountOfRange = myRange.count

现在无法在 swift3 中执行此操作

var str = "Hello, playground"

let myRange = str.range(of: "Hello")

let myCountOfRange = myRange.count // type index does not conform to protocol strideable 

在 Swift3 中,要找到范围的大小,您可以执行以下操作:

var str = "Hello, playground"

let myRange = str.range(of: "Hello")

let myCountOfRange = str[myRange!].characters.count

我不知道这是否是最好的方法,但它确实有效。

或者:

let myCountOfRange = str.distance(from: myRange!.lowerBound, to: myRange!.upperBound)

两者都需要访问原始 collection(即字符串),这显然是 Swift 的限制 3. 讨论了 collection 和索引的新模型here.


如果您想将范围存储在数组中并对其调用 .count.last,您可以将 Range<Index> 转换为 CountableRange<Int>,同时您仍然可以访问 collection:

var str = "Hello, playground"

let myRange = str.range(of: "Hello")!

let lb = str.distance(from: str.startIndex, to: myRange.lowerBound) as Int
let ub = str.distance(from: str.startIndex, to: myRange.upperBound) as Int

let newRange = lb..<ub
newRange.count  // 5
newRange.last   // 4