Data.txt contains stuff like this : "Cat" "Dog" "Mouse"
I want to fill an array with strings from that file (dico[0] = "Cat", dico[1] = "Dog", aso).
I found this, How to call Objective-C's NSArray class method from within Swift? and Read and write data from text file, but when I use this code :
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSArray(contentsOfFile: path)
println("\(dico[0])")
println("\(dico.count)")
All I get is "nil" and "0".
I guess data in my file aren't written the way they should be and the code I use isn't right, but I can't figure why.
Moreover, when I use this code, it's OK :
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSString(contentsOfFile: path)
println("\(dico)")
The problem is that I don't want dico to be a string, I want it to be an array.
Way 1: Using a Naive Approach Get the string. Create a character array of the same length as of string. Traverse over the string to copy character at the i'th index of string to i'th index in the array. Return or perform the operation on the character array.
We can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array.
The fill() method fills specified elements in an array with a value. The fill() method overwrites the original array. Start and end position can be specified. If not, all elements will be filled.
This is not how arrayWithContentsOfFile
works.
It expects as its argument the path to a file containing a string representation of an array produced by the writeToFile:atomically:
method.
For your purposes, you can use the second approach, complemented by calling componentsSeparatedByString()
on your string.
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSString(contentsOfFile: path).componentsSeparatedByString("\n")
NSArray's arrayWithContentsOfFile:
initializer isn't meant to be used with regular text file. It's only meant to be used with files that were created using NSArray's writeToFile:atomically:
Assuming you want to split up the words in your text file into an array and assuming each word will be separated by a space, you can do something like this:
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSString(contentsOfFile: path)
let components = dico.componentsSeparatedByString(" ")
println("\(components)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With