1

I'm reading from a file with the following data:

-LX-A7q4_8kFE4I_-iip,1
-LWyCOhwO_lUwMt-dOOa,1
-LWwVCZL5sfQYd4WtSHw,1

Each row is separated by "\n", and each element is separated by a comma.

I am able to read the file, put the contents into an array, with the correct rows and columns.

I am then able to filter the array to remove the row I want. Finally, I want to write the array back to the file in the same format. The code I have is as follows:

// This filters the array and gets me the rows I want.  
func writeToFile() {          
    let filteredMessageID = result.filter { $0.messageID != nominationKeyForReadStatus }
    //This is my attempt at converting the array to a string, before I try writing the string back to the file.  
    let filteredMessageIDJoinedString = filteredMessageID.joined(separator:"\n")
}

This last bit of code is clearly wrong, as my array, returned after filtering as filteredMessageID is as follows:

// ▿ 2 elements
  ▿ 0 : 2 elements
    - messageID : "-LWyCOhwO_lUwMt-dOOa"
    - readStatus : "1"
  ▿ 1 : 2 elements
    - messageID : "-LWwVCZL5sfQYd4WtSHw"
    - readStatus : "1"

How do I convert filteredMessageID back to a string that looks like this?

"-LWyCOhwO_lUwMt-dOOa,1\n-LWwVCZL5sfQYd4WtSHw,1"

Thanks in advance!

1 Answer 1

1

You need a map before the joined to transform each of the tuples to a String:

let filteredMessageIDJoinedString = filteredMessageID
    .map{ "\($0.messageID),\($0.readStatus)" } // notice the comma in the middle
    .joined(separator:"\n")

Your format looks like CSV. You can find out how to read and write CSV with Swift here.

Sign up to request clarification or add additional context in comments.

2 Comments

@nm1213 Is there a problem with my answer?
Sweeper, not at all. It worked perfectly. I’m still working on the function to complete it, but your solution is exactly the right approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.