serialization - Saving Arrays in Swift -
i have question saving arrays in apple's new programming language swift. in objective-c saved data nsfilemanager
... doesn't work anymore in swift. wanted ask how should save array without using nsuserdefaults isn't suited storing big amount of data. appreciate :]
first (if array not of string type) change string:
var notstringarray = [1, 2, 3, 4] var array: [string] = [] value in notstringarray{ array.append(string(value)) }
then reduce array 1 string:
var array = ["1", "2", "3", "4", "5"] //ignore line if array wasn't of type string , did step above var stringfromarray = reduce(array, "") { $0.isempty ? $1 : "\($0)\n\($1)" }
this create string looks this:
"1 2 3 4 5"
and write , read file add class @ top of file:
class file { class func open (path: string, utf8: nsstringencoding = nsutf8stringencoding) -> string? { var error: nserror? // return nsfilemanager().fileexistsatpath(path) ? string(contentsoffile: path, encoding: utf8, error: &error)! : nil } class func save (path: string, filecontent: string, utf8: nsstringencoding = nsutf8stringencoding) -> bool { var error: nserror? // return filecontent.writetofile(path, atomically: true, encoding: utf8, error: &error) } }
(don't forget import uikit)
to save file:
let didsave = file.save("directoryoffile", content: stringfromarray) if didsave { println("file saved") } else { println("error saving file") }
to back:
var stringfromfile = "" if let loaddata = file.open("directoryoffile") { stringfromfile = loaddata } else { println("error reading file") }
to put in array:
var newarray: [string] = [] //creates empty string array newarray = stringfromfile.componentsseparatedbystring("\n")
and there have it
Comments
Post a Comment