iosswiftalgorithmnsarraystringbuilder

Swift Printing an Array in a table form String and also adding special characters


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

Solution


Use map for each property and join it to create a comma separated row. Then using the results in an array join again with a new line character.

let csv = [array.map(\.name).joined(separator: ","),
           array.map(\.id).joined(separator: ","),
           array.map(\.age).joined(separator: ",")]
   .joined(separator: "\n")