【问题标题】:Replacement for enumerateSubstringsInRange in Swift 3在 Swift 3 中替换 enumerateSubstringsInRange
【发布时间】:2016-07-23 19:53:23
【问题描述】:

我正在将代码从 Swift 2 升级到 Swift 3 并遇到此错误:

wordcount.swift:7:5: 错误:'String' 类型的值没有成员 'enumerateSubstringsInRange' line.enumerateSubstringsInRange(range, options: .ByWords) {w,,,_ in

在 Swift 2 中,此方法来自编译器知道的 String 扩展。

我无法在 Swift 3 库中找到此方法。它出现在Foundation 的文档中:

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instm/NSString/enumerateSubstringsInRange:options:usingBlock:

我的整个脚本是:

import Foundation

var counts = [String: Int]()

while let line = readLine()?.lowercased() {
    let range = line.characters.indices
    line.enumerateSubstringsInRange(range, options: .ByWords) {w,_,_,_ in
        guard let word = w else {return}
        counts[word] = (counts[word] ?? 0) + 1
    }
}

for (word, count) in (counts.sorted {$0.0 < $1.0}) {
    print("\(word) \(count)")
}

它适用于 Swift 2.2(以我已经为 Swift 3 所做的更改为模,例如 lowercase -> lowercasedsort -> sorted)但无法使用 Swift 3 编译。

而且非常奇怪的是,Swift 3 命令行编译器和 XCode 8 Beta 中的 Swift 迁移助手都没有建议替换,就像许多其他重命名的方法一样。也许enumerateSubstringsInRange 已被弃用或它的参数名称已更改?

【问题讨论】:

  • 改成enumerateSubstrings(in: range, options: .ByWords) {}

标签: ios swift string foundation


【解决方案1】:

如果您在 Playground 中键入 str.enumerateSubstrings,您将看到以下作为完成选项:

enumerateSubstrings(in: Range<Index>, options: EnumerationOptions, body: (substring: String?, substringRange: Range<Index>, enclosingRange: Range<Index>, inout Bool) -> ())

除了解决新的enumerateSubstrings(in:options:body:) 语法之外,您还需要更改获取字符串range 的方式:

import Foundation

var counts = [String: Int]()

while let line = readLine()?.lowercased() {
    let range = line.startIndex ..< line.endIndex
    line.enumerateSubstrings(in: range, options: .byWords) {w,_,_,_ in
        guard let word = w else {return}
        counts[word] = (counts[word] ?? 0) + 1
    }
}

for (word, count) in (counts.sorted {$0.0 < $1.0}) {
    print("\(word) \(count)")
}

【讨论】:

  • 太棒了。我应该猜到这是新方法,因为我已经看到许多修复,例如 joinWithSeparator(_:) 变成 joined(separator:)
  • 为什么要这么复杂?难道不应该比 Obj-C 更简单,你只需使用NSMakeRange(0, line.length)吗?
  • @IulianOnofrei,我分享你的挫败感。 Swift 的设计者让 Strings 比以前更有能力,但有时使用它们会有点困难。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-05
  • 1970-01-01
  • 2022-10-25
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多