ios - 在 Swift 中解析 CSV 文件并将其加载到 Core Data 中

标签 ios swift xcode csv core-data

我正在处理 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
    }

第五行:

if let content = String(contentsOfURL:contentsOfURL,encoding:encoding,error:error){

抛出以下错误:

参数标签“(contentsOfURL:、encoding:、error:)”与任何可用的重载不匹配

这超出了我的理解和技能水平。我实际上只是想找到将逗号分隔的 .csv 文件导入核心数据对象的最佳方法。

如有任何帮助,我们将不胜感激。 Simon Ng 的原始示例似乎非常适合我想要实现的目标。只是已经很久没有更新了。

最佳答案

首先 - 你们都是杰出的贡献者,并且对情报的了解非常快。我要感谢大家这么快的答复。在这里,我最终得到了最新 Swift 5 语法中的特定函数。

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) {
    if let content = try? String(contentsOf: contentsOfURL as URL, encoding: encoding) {
        items = []
        let lines:[String] = content.components(separatedBy: NSCharacterSet.newlines) 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
}

关于ios - 在 Swift 中解析 CSV 文件并将其加载到 Core Data 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55733383/

相关文章:

iOS 应用程序配置文件错误,配置文件未关联

ios - 如何控制音乐播放器的耳机?

swift - 如何在labels-swift上显示经纬度

ios - 如何更改来自不同结构的@State 变量

ios - 如何在按下 Ctrl 键时在 XCode 中滚动 Storyboard

iphone - 如何检查连接到互联网的 url?

ios - iPhone应用程序断开连接后如何知道互联网变为事件状态

iphone - iOS 创建标签列表

ios - 访问多个函数中的可选属性以进行计算 - Swift

swift - 如何从第一个选项卡到达第二个选项卡导航堆栈?