1

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
2
  • @son i wish i understood what you mean by saving the string into an internal property may be a reference or code may help Commented Apr 12, 2022 at 10:35
  • I we focus on only the first 2, do you want "Adam,3907,48\nBeth,17945,2" or "Adam,Beth\n3907,17945\n48,2" Commented Apr 12, 2022 at 10:53

1 Answer 1

4

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")
Sign up to request clarification or add additional context in comments.

4 Comments

your answer does not print is the desired order, ive updated my question
@BigFire See my updated answer
its wierd i get this strange error from my playground solution.swift:39:89: error: type of expression is ambiguous without more context let csv : String = [sortedArray.map(\.name).joined(separator: ","),sortedArray.map(\.id).joined(separator:","),sortedArray.map(\.age).joined(separator: ",")].joined(separator: "\n")
You are using the exact same code as in my answer and it works for me. Also when I copy all code from the question and run it together with my answer it works fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.