swift - 在 Swift 3 中计算范围计数

标签 swift swift3

显然在 Swift 3 之前,一个 Range<String.Index>有一个count属性(property)。在迁移到 Swift 3 时,我注意到这个 count属性(property)现在没有了。如何计算 2 String.Index 之间的距离es 在 Swift 3 中?

最佳答案

从 Swift 3 开始,所有索引计算都由集合本身完成, 比较 SE-0065 – A New Model for Collections and Indices关于 Swift 演进。

例子:

let string = "abc 1234 def"
if let range = string.range(of: "\\d+", options: .regularExpression) {
    let count = string.distance(from: range.lowerBound, to: range.upperBound)
    print(count) // 4
}

实际上,String 不是 Swift 3 中的集合,但它有那些方法 以及它们被转发到字符串 CharacterView。 你得到与

相同的结果
let count = string.characters.distance(from: range.lowerBound, to: range.upperBound)

从 Swift 4 开始,字符串(再次)是集合。

关于swift - 在 Swift 3 中计算范围计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39505923/

相关文章:

ios - 使用 Swift 将按钮添加到静态 TableView 标题

ios - 我想像在 JIOtv App 中那样创建 collectionView。这是新东西,互联网上没有答案

ios - 从 Collection View 中的可重用单元格中获取按钮单击(XIB文件)

swift - Swift 3.x 中的矩阵和对角化

ios - iPhone 不振动

Xcode Beta 6.1 和 Xcode 6 GM 因奇怪的原因卡住了索引

swift - 在 NSButton 中定位 NSImage

ios - TableView 中出现意外的非空返回值

swift - 使用 AFNetworking 快速下载文件

ios - 具有唯一标识符的UIButton