Friday, 15 February 2013

swift - Fill an array with strings from a txt file -



swift - Fill an array with strings from a txt file -

data.txt contains stuff this : "cat" "dog" "mouse"

i want fill array strings file (dico[0] = "cat", dico[1] = "dog", aso).

i found this, how phone call objective-c's nsarray class method within swift? , read , write info text file, when utilize code :

let bundle = nsbundle.mainbundle() allow path = bundle.pathforresource("data", oftype: "txt") allow dico = nsarray(contentsoffile: path) println("\(dico[0])") println("\(dico.count)")

all "nil" , "0".

i guess info in file aren't written way should , code utilize isn't right, can't figure why.

moreover, when utilize code, it's ok :

allow bundle = nsbundle.mainbundle() allow path = bundle.pathforresource("data", oftype: "txt") allow dico = nsstring(contentsoffile: path) println("\(dico)")

the problem don't want dico string, want array.

this not how arraywithcontentsoffile works.

it expects argument path file containing string representation of array produced writetofile:atomically: method.

for purposes, can utilize sec approach, complemented calling componentsseparatedbystring() on string.

let bundle = nsbundle.mainbundle() allow path = bundle.pathforresource("data", oftype: "txt") allow dico = nsstring(contentsoffile: path).componentsseparatedbystring("\n")

arrays swift

No comments:

Post a Comment