Lets assume i have this string
var stringCSV = "Beth,Charles,Danielle,Adam,Eric\n17945,10091,10088,3907,10132\n2,12,13,48,11";
And i converted it into a 2D Array
[["Beth", "Charles", "Danielle", "Adam", "Eric"], ["17945", "10091", "10088", "3907", "10132"], ["2", "12", "13", "48", "11"]]
Below is the code i used to convert the String into a 2D Array and sort it.
struct Person {
let name: String
let id: String
let age: String
}
var csvFormatted = [[String]]()
stringCSV.enumerateLines { (line, _) in
var res = line.split(separator: ",",omittingEmptySubsequences: false).map{
String($0)
}
for i in 0 ..< res.count {
res[i] = res[i]
}
csvFormatted.append(res)
}
let properties = zip(csvFormatted[1],csvFormatted[2])
let namesAndProperties = zip(csvFormatted[0],properties)
let structArray = namesAndProperties.map { (name, properties) in
return Person(name: name, id: properties.0, age: properties.1)
}
let sortedArray = structArray.sorted {
return $0.name < $1.name
}
for i in sortedArray {
print(i.name, i.id, i.age)
}
i get the below output
Adam 3907 48
Beth 17945 2
Charles 10091 12
Danielle 10088 13
Eric 10132 11
But I wont to understand and know how i can print the sorted array back to string, just like it was before i splitted it into an array and sorted it and including the special characters like "\n" and ",".
and achieve something the below
Adam,Beth,Charles,Danielle,Eric\n
3907,17945,10091,10088,10132\n
48,2,12,13,11
"Adam,3907,48\nBeth,17945,2"or"Adam,Beth\n3907,17945\n48,2"