【发布时间】:2019-04-17 17:50:31
【问题描述】:
我正在处理之前关于 AppCode 的一篇名为“核心数据基础:预加载数据和使用现有 SQLite 数据库”的帖子,位于此处:https://www.appcoda.com/core-data-preload-sqlite-database/
在 Simon Ng 的帖子中,有一个名为 parseCSV 的函数,它完成了扫描 .csv 并将其分解为相应的行的所有繁重工作,这样每一行的元素就可以保存到核心数据中各自的 managedObjectContext 中。
不幸的是,所有代码似乎都是用 Swift 1.0 或 Swift 2.0 编写的,我无法理解将其转换为 Swift 4 时遇到的错误。
我已将 Xcode 建议的关于“this”的所有更改都替换为“that”,最后一个错误告诉我“Argument labels '(contentsOfURL:, encoding:, error:)' do不匹配任何可用的重载”,我无法理解或纠正。
//https://www.appcoda.com/core-data-preload-sqlite-database/
func parseCSV (contentsOfURL: NSURL, encoding: String.Encoding, error: NSErrorPointer) -> [(name:String, detail:String, price: String)]? {
// Load the CSV file and parse it
let delimiter = ","
var items:[(name:String, detail:String, price: String)]?
if let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error) {
items = []
let lines:[String] = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String]
for line in lines {
var values:[String] = []
if line != "" {
// For a line with double quotes
// we use NSScanner to perform the parsing
if line.range(of: "\"") != nil {
var textToScan:String = line
var value:NSString?
var textScanner:Scanner = Scanner(string: textToScan)
while textScanner.string != "" {
if (textScanner.string as NSString).substring(to: 1) == "\"" {
textScanner.scanLocation += 1
textScanner.scanUpTo("\"", into: &value)
textScanner.scanLocation += 1
} else {
textScanner.scanUpTo(delimiter, into: &value)
}
// Store the value into the values array
values.append(value! as String)
// Retrieve the unscanned remainder of the string
if textScanner.scanLocation < textScanner.string.count {
textToScan = (textScanner.string as NSString).substring(from: textScanner.scanLocation + 1)
} else {
textToScan = ""
}
textScanner = Scanner(string: textToScan)
}
// For a line without double quotes, we can simply separate the string
// by using the delimiter (e.g. comma)
} else {
values = line.components(separatedBy: delimiter)
}
// Put the values into the tuple and add it to the items array
let item = (name: values[0], detail: values[1], price: values[2])
items?.append(item)
}
}
}
return items
}
第 5 行:
if let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error) {
抛出以下错误:
参数标签 '(contentsOfURL:, encoding:, error:)' 不匹配任何可用的重载
这超出了我的理解和技能水平。我真的只是想找到将逗号分隔的 .csv 文件导入核心数据对象的最佳方法。
我们将不胜感激。 Simon Ng 的原始示例似乎非常适合我想要实现的目标。好久没更新了。
【问题讨论】:
-
让 Xcode 通过使用代码完成来提供帮助。键入
if let content = String.init(,它将显示可用的初始化程序。一旦你得到你想要的,你可以删除.init。 -
请参阅stackoverflow.com/questions/24010569/…,但还有许多其他问题。在 Swift 3 中,语法发生了很大变化。
-
从 rmaddy 学到了一些新东西——在格式化代码完成时,在 ol' .init 中折腾确实提供了额外的帮助。谢谢rmaddy!
-
我得告诉你——我很惊讶我这么快就得到了很大的帮助。所有伟大的阅读。谢谢大家。
标签: ios swift xcode csv core-data