0

I have a Test.txt file saved in Documents Directory of an app. There are several names saved one by one in each line in the Test.txt file, like this:

Tom
Jack
Jerry
Jennifer
Lynn

I would like to add these names to an array, like this:

var nameList = ["Tom", "Jack", "Jerry", "Jennifer", "Lynn"]

Is there any way to get it work?

I have the following codes, but it will consider the names as one string.

  if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let archiveURL = dir.appendingPathComponent("Test").appendingPathExtension("txt")

            do {

                try Data(textView.text.utf8).write(to: archiveURL)
            }

            catch {
                print("error")
            }

            do {
                namesPool = try! [String(contentsOf: archiveURL, encoding: .utf8)]
            }

        }

The above codes will get the following array:

var nameList = ["Tom\nJack\nJerry\nJennifer\nLynn\n"]

Any suggestions would be appreciated.

Vincent
  • 486
  • 6
  • 20

2 Answers2

0

You are missing one last step, separate it using:

let namesTogether = try! String(contentsOf: archiveURL, encoding: .utf8)
namesPool = namesTogether.components(separatedBy: "\n")
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
0

Swift 4

// String with multiple names separated by end of line
let nameStr = try! String(contentsOf: archiveURL, encoding: .utf8)
// array of Substrings
let nameArray = nameStr.split(separator: "\n") 
// first name as String
let name = String(nameArray[0])

More about handling strings:Strings Cheat Sheet

Tomasz Czyżak
  • 1,118
  • 12
  • 13
  • Thanks a lot, Tomasz. It works in a way. But I will save some other names to this Test.txt file sometimes. It will get an error: "Cannot assign value of type '[ArraySlice]' to type '[String]'", if the namesPool is dynamic. – Vincent Oct 22 '17 at 08:44
  • https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html `split(separator:)` returns an array of `Substring`s, instead of `String`s. Considering that `Substring` is supposed to be used as a intermediate type while working with strings (see the link above), in this particular case I would still go with `components(separatedBy:)` since he wants that list of strings as a final result and is not manipulating them further – Milan Nosáľ Oct 22 '17 at 08:45
  • @user174782 see edited response – Tomasz Czyżak Oct 23 '17 at 07:14