Ray*_*oal 9 string foundation ios swift
我正在将代码从Swift 2升级到Swift 3并遇到此错误:
wordcount.swift:7:5:错误:类型'字符串'的值没有任何部件'enumerateSubstringsInRange' line.enumerateSubstringsInRange(范围选择:.ByWords){W, ,,_在
在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)")
}
Run Code Online (Sandbox Code Playgroud)
它适用于Swift 2.2(模块化我已经为Swift 3做的更改,例如lowercase- > lowercased和sort- > sorted)但无法使用Swift 3进行编译.
而且非常奇怪的是,Swift 3命令行编译器和XCode 8 Beta中的Swift Migration助手都没有像其他许多其他重命名方法那样建议替换.可能enumerateSubstringsInRange已弃用或其参数名称已更改?
如果您输入str.enumerateSubstringsPlayground,您将看到以下内容作为完成选项:
enumerateSubstrings(in: Range<Index>, options: EnumerationOptions, body: (substring: String?, substringRange: Range<Index>, enclosingRange: Range<Index>, inout Bool) -> ())
Run Code Online (Sandbox Code Playgroud)
除了解决新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)")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2978 次 |
| 最近记录: |