Text File to String Array?

How do I read a text file into a String array? Do I need to upload my text files into my Assets catalogue?

You don't (can't) put a text file into an Assets catalog. What I would do is this:


1. Create the text file using UTF-8 encoding.


2. Add the text file to your project, and check its target membership checkbox (in the File inspector). This causes Xcode to add the file to the Resources subdirectory of your app bundle.


3. In your code, use the "Bundle.url(forResource:withExtension:)" method to get a URL to the string resource file.


4. Read the file using the "String (contentsOf:encoding:)" initializer.


5. Use the "components(separatedBy:.newlines)" method to create your array.

Hi,

Below code from one of my study project.

if let startWordsPath = Bundle.main.path(forResource: "yourtextfilename", ofType: "txt")
        {
            if let startWords = try? String(contentsOfFile: startWordsPath)
            {
                allWords = startWords.components(separatedBy: "\n")
                print ("allWords count = \(allWords.count)")
            }
            else
            {
                allWords = ["error"]
            }
        }


Cheers, glnj

Text File to String Array?
 
 
Q