user13941931
user13941931

Reputation:

How do I import text from a file into an array?

Suppose I have an array: var arr = [[]], and I have a text file which contains the array like this:

[["R", "T", "A", "N", "T", "D", "G", "P", "E", "P"],
["O", "W", "N", "A", "U", "D", "N", "Z", "E", "Y"]]

How would I put the array from the text file into the var arr = [[]] I just created? I tried this, but it just says "String from content can not be put into type [[Any]]"

if let filepath = Bundle.main.path(forResource: "example", ofType: "txt") {
    do {
        let contents = try String(contentsOfFile: filepath)
        arr = contents
    } catch {
        // contents could not be loaded
    }
} else {
    // example.txt not found!
}

Upvotes: 0

Views: 68

Answers (2)

PGDev
PGDev

Reputation: 24341

You can use JSONDecoder to decode the String data in file,

var arr = [[String]]()

if let filepath = Bundle.main.path(forResource: "example", ofType: "txt") {
    do {
        let contents = try String(contentsOfFile: filepath)
        if let data = contents.data(using: .utf8) {
            arr = try JSONDecoder().decode([[String]].self, from: data)
            print(arr)
        }
    } catch {
        print(error)
    }
} else {
    print("File not found")
}

Upvotes: 1

Satyendra Chauhan
Satyendra Chauhan

Reputation: 328

You can try this

 let contents = try String(contentsOfFile: filepath)
 let data = contents.data(using: .utf8)!
 let array = try? JSONSerialization.jsonObject(with: data, options: 
      .allowFragments) as? [[String]]

Upvotes: 0

Related Questions