18

I was wondering what the simplest and cleanest to read a text file into an array of strings is in swift.

Text file:

line 1
line 2
line 3 
line 4

Into an array like this:

var array = ["line 1","line 2","line 3","line 4"]

I would also like to know how to do a similar thing into struct like this:

Struct struct{
   var name: String!
   var email: String!
}

so take a text file and put it into struct's in an array.

Thanks for the help!

2

7 Answers 7

18

Updated for Swift 3

    var arrayOfStrings: [String]?

    do {
        // This solution assumes  you've got the file in your bundle
        if let path = Bundle.main.path(forResource: "YourTextFilename", ofType: "txt"){
            let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)                
            arrayOfStrings = data.components(separatedBy: "\n")
            print(arrayOfStrings)
        }
    } catch let err as NSError {
        // do something with Error
        print(err)
    }
Sign up to request clarification or add additional context in comments.

1 Comment

is there a version for swift5 out there somewhere? :)
17

First you must read the file:

let text = String(contentsOfFile: someFile, encoding: NSUTF8StringEncoding, error: nil)

Then you separate it by line using the componentsSeparatedByString method:

let lines : [String] = text.componentsSeparatedByString("\n")

2 Comments

Note that some files do not just \n as the new line marker. You can consider using NSCharacterSet.newlineCharacterSet() and componentsSeparatedByCharactersInSet.
new Swift syntax would be: try! let text = String(contentsOfFile: someFile!, encoding: NSUTF8StringEncoding) stackoverflow.com/questions/32663872/…
6

Updated for Swift 5:

The const path contains the file path.

do {
    let path: String = "file.txt"
    let file = try String(contentsOfFile: path)
    let text: [String] = file.components(separatedBy: "\n")
} catch let error {
    Swift.print("Fatal Error: \(error.localizedDescription)")
}

If you want to print what's inside of file.txt line by line:

for line in text {
    Swift.print(line)
}

2 Comments

is there a version for swift5 out there somewhere? :)
thanks muchly! :) and how would i be able to output that content into an Array? (one textfile, one Array)
2

Here is a way to convert a string to an array(Once you read in the text):

var myString = "Here is my string"

var myArray : [String] = myString.componentsSeparatedByString(" ")

This returns a string array with the following values: ["Here", "is", "my", "string"]

Comments

2

Swift 4:

do {
    let contents = try String(contentsOfFile: file, encoding: String.Encoding.utf8)
    let lines : [String] = contents.components(separatedBy: "\n")    
} catch let error as NSError {
    print(error.localizedDescription)
}

1 Comment

is there a version for swift5 out there somewhere? :)
1

In Swift 3 for me worked like below:

Import Foundation

let lines : [String] = contents.components(separatedBy: "\n")

Comments

0

Updated so you don't need to hardcode the file path:

Because Xcode requires you to use unique filenames inside a project, we can simply search for the filename inside the main bundle. This approach eliminates the need to hardcode the file path, thereby preventing potential issues, especially when collaborating with others / working on different machines:

import Foundation

extension Bundle {
    /// Creates an array of strings from a text file in the bundle.
    /// - Parameters:
    ///   - fileName: The name of the text file.
    ///   - separatedBy: The string used to separate the contents of the file.
    /// - Returns: An array of strings representing the contents of the file, separated by the specified separator.
    /// - Note: Will raise a fatal error if the file cannot be located in the bundle or if the file cannot be decoded as a String.
    func createArrayOfStringsFromTextFile(fileName file: String, separatedBy separator: String) -> [String] {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Failed to locate '\(file)' in bundle.")
        }
        
        guard let fileContent = try? String(contentsOf: url)  else {
            fatalError("Failed to read content of '\(file)' as a string.")
        }
        let result: [String] = fileContent.components(separatedBy: separator)
        return result
    }
}

Usage:

let result: [String] = Bundle.main.createArrayOfStringsFromTextFile(fileName: "someFile.txt", separatedBy: "\n")

Comments

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.