我将代码从Swift 2升级到Swift 3并遇到了这个错误:
wordcount.swift:7:5:错误:类型'字符串'的值没有会员&enumerateSubstringsInRange' line.enumerateSubstringsInRange(范围,选项:.ByWords){w,,,_ in
在Swift 2中,此方法来自编译器可识别的String
扩展名。
我无法在Swift 3库中找到此方法。它出现在Foundation
的文档中:
我的整个脚本是:
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
- &gt; lowercased
和sort
- &gt ; sorted
)但无法使用Swift 3进行编译。
非常奇怪的是,Swift 3命令行编译器和XCode 8 Beta中的Swift Migration助手都没有像其他许多重命名方法那样建议替换。可能不推荐enumerateSubstringsInRange
或其参数名称已更改?
答案 0 :(得分:8)
如果您在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)")
}