Showing posts with label CSV. Show all posts
Showing posts with label CSV. Show all posts

Sunday, September 11, 2016

How to split CSV in Swift

Below is Swift 2.1 code
Swift 3 code is here https://github.com/Daniel1of1/CSwiftV/blob/master/Sources/CSwiftV.swift
csvsplit.swift   Select all
//: Playground - noun: a place where people can play import Foundation public func split(string: String, _ separator: String = ",") -> [String] { // Swift 2.1 //public func split(_ string: String, _ separator: String = ",") -> [String] { // Swift 3 func oddNumberOfQuotes(string: String) -> Bool { // Swift 2.1 // func oddNumberOfQuotes(_ string: String) -> Bool { // Swift 3 return string.componentsSeparatedByString("\"").count % 2 == 0 // Swift 2.1 // return string.components(separatedBy: "\"").count % 2 == 0 // Swift 3 } let initial = string.componentsSeparatedByString(separator) // Swift 2.1 // let initial = string.components(separatedBy: separator) // Swift 3 var merged = [String]() for newString in initial { if let record = merged.last { guard oddNumberOfQuotes(record) == true else { merged.append(newString) continue } merged.removeLast() let lastElem = record + separator + newString merged.append(lastElem) } else { merged.append(newString) continue } } return merged } public func csvsplit(string: String, _ rowSeparator: String = "\n", _ colSeparator: String = ",") -> [[String]] { // Swift 2.1 //public func csvsplit(_ string: String, _ rowSeparator: String = "\n", _ colSeparator: String = ",") -> [[String]] { // Swift 3 return split(string.stringByReplacingOccurrencesOfString("\r\n", withString: "\n"), rowSeparator).map{split($0, colSeparator)} // Swift 2.1 // return split(string.replacingOccurrences(of: "\r\n", with: "\n"), rowSeparator).map{split($0, colSeparator)} // Swift 3 } print(csvsplit("aa,\"b,b\",cc\na,b,c")) do { // www.quandl.com api : anonymous user limit of 50 calls per day. let csv = try String(contentsOfURL: NSURL(string: "https://www.quandl.com/api/v3/datasets/FRED/DEXJPUS.csv")!, encoding: NSUTF8StringEncoding) // Swift 2.1 // let csv = try String(contentsOf: Foundation.URL(string: "https://www.quandl.com/api/v3/datasets/FRED/DEXJPUS.csv")!) // Swift 3 // there are over 11 000 rows from this url, so playground will take some times to finish print(split(csv,"\n")[0...2].map{split($0)}) } catch let error { print(error) }