I have a string that I got from a text file.
Text file:
Line 1
Line 2
Line 3
...
I want to convert it to an array, one array element p
Swift 4:
I would recommend to first save your CSV into string if you haven't already done it, then "clean" the string by removing unnecessary carriage returns
let dataString = String(data: yourData!, encoding: .utf8)!
var cleanFile = dataString.replacingOccurrences(of: "\r", with: "\n")
cleanFile = cleanFile.replacingOccurrences(of: "\n\n", with: "\n")
Above will give you a string with a most desirable format, then you can separate the string using \n as your separator:
let csvStrings = cleanFile.components(separatedBy: ["\n"])
Now you have an array of 3 items like:
["Line1","Line2","Line3"]
I am using a CSV file and after doing this, I am splitting items into components, so if your items were something like:
["Line1,Line2,Line3","LineA,LineB,LineC"]
let component0 = csvStrings[0].components(separatedBy: [","]) // ["Line1","Line2","Line3"]
let component1 = csvStrings[1].components(separatedBy: [","]) // ["LineA","LineB","LineC"]
in Xcode 8.2, Swift 3.0.1:
Use NSString method components(separatedBy:)
let text = "line1\nline2"
let array = text.components(separatedBy: CharacterSet.newlines)
Or use String method enumerateLines, like Leo Dabus
's answer
let test1 = "Line1\n\rLine2\nLine3\rLine4"
let t1 = test1.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let t2 = t1.filter{ $0 != "" }
let t3 = t1.filter{ !$0.isEmpty }